Object.defineProperty vs vanilla
Given the main use case, do
foo.bar = 'baz';
and
Object.defineProperty(foo, 'bar', {
value: 'baz',
configurable: true,
enumerable: true,
writable: true
});
behave exactly the same in supported browsers?
Is it possible to go back to vanilla in pre-ES6 apps just because of the favorable syntax, or mix them up without any side effects?
source to share
Yes, they behave the same when
- there is
foo
no propertybar
(not even inherited), so a new one is created, or - there is a property
bar
that has attributeswritable
andconfigurable
set totrue
However, if none of these are listed, they do give slightly different results.
-
defineProperty
ignores inherited properties and their descriptors - If an existing (possibly inherited) property is an accessory, the assignment will try to call the setter (and fail if it doesn't exist), while
definePropery
overwriting the property with a data descriptor (or fail if it's native, non-configurable) - If the existing inherited property is a data property, the assignment will fail if
writable
false, or create a new own property if true, for exampledefineProperty
always - If the existing native property is a data property, the assignment will fail if
writable
false, or set a new value if true, butdefineOwnProperty
fail if ifconfigurable
is false, and overwrite the attributes otherwise.
Considering the main use case
If by "basic usage" you don't mean fancy property attributes, then yes, they are equivalent. However, you should just use simple assignments as they are easier to read and faster to complete.
Can we go back to vanilla in pre ES6 apps?
Note that full support defineProperty
comes with ES5, so if you don't have to consider pre-ES5 (old IE) browsers, you don't care.
source to share