Object.defineProperty vs vanilla property

吃可爱长大的小学妹 提交于 2019-12-12 15:41:00

问题


Considering the basic scenario of usage, do

foo.bar = 'baz';

and

Object.defineProperty(foo, 'bar', {
  value: 'baz',
  configurable: true,
  enumerable: true,
  writable: true
});

behave exactly the same in supported browsers?

Can we fall back to vanilla in pre-ES6 applications just because of favourable syntax or mix both of them without any side effects?


回答1:


Yes, they behave the same when

  • there is no bar property in foo (not even an inherited one), so a new one is created, or
  • there is a bar property that has the writable and configurable attributes set to true

However, if neither of those is given, the two indeed produce slightly different results.

  • defineProperty does not consider inherited properties and their descriptors
  • If the existing (possibly inherited) property is an accessor, the assignment will try to call the setter (and fail if none exists), while definePropery will overwrite the property with the data descriptor (or fail if it is an own, non-configurable one)
  • If an existing inherited property is a data property, the assignment will fail if writable is false, or create a new own property if true, like the defineProperty always does
  • If an existing own property is a data property, the assignment will fail if writable is false, or set the new value if true, while defineOwnProperty will fail iff configurable is false and overwrite the attributes otherwise.

Considering the basic scenario of usage

If by "basic usage" you mean no usage of fancy property attributes, then yes they are equivalent. Yet you should just use the simple assignments, for they are easier to read and faster to execute.

Can we fall back to vanilla in pre-ES6 applications

Notice that full support of defineProperty comes with ES5, so unless you need to consider pre-ES5 (old IE) browsers you wouldn't care at all.



来源:https://stackoverflow.com/questions/29861269/object-defineproperty-vs-vanilla-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!