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?

+2


source to share


1 answer


Yes, they behave the same when

  • there is foo

    no property bar

    (not even inherited), so a new one is created, or
  • there is a property bar

    that has attributes writable

    and configurable

    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 example defineProperty

    always
  • If the existing native property is a data property, the assignment will fail if writable

    false, or set a new value if true, but defineOwnProperty

    fail if if configurable

    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.

+3


source







All Articles