简体   繁体   中英

Does Object.defineProperty check if the property is defined?


I need to define property for a javascript object.
var obj = {};
obj['prop1'] = 1


In the above way, we can define the property.
Now, let us use Object.defineProperty
var obj = {}; Object.defineProperty(obj,'prop1',{value:1});
this is alternate way.

what is the difference between the two?
Does Object.defineProperty check if the property is already defined or not??
I believe obj['prop1'] = 1 checks for the property
thanks :)

EDIT
Any performance variation in between those?

Neither a direct object access, nor Object.defineProperty will " check " for existing properties. The only difference between those two is the possbility, to modify property descriptor values .

Property descriptors are

  • enumerable
  • configurable
  • writable

which are all set to true by using direct property access . With Object.defineProperty you have the option to set these properties individually. I suggest you read this MDN articl e to get an idea about the meanings.

If for instance, a propertie owns the flag configurable=false , you cannot overwrite or delete it (which might be the case for your issue).


Concerning performance:

Since Object.defineProperty is a function which needs to get executed each time, it has to be slower than a direct access on the object. I created this little benchmark:

http://jsperf.com/property-access-with-defineproperty

However, even if the difference looks drastically, you may not forget the value and reason for Object.defineProperty .

在这两种情况下,如果属性存在,它的值将被覆盖,否则将被创建

Mozilla says :

When the property already exists, Object.defineProperty() attempts to modify the property according to the values in the descriptor and the object's current configuration. If the old descriptor had its configurable attribute set to false (the property is said to be "non-configurable"), then no attribute besides writable can be changed. In that case, it is also not possible to switch back and forth between the data and accessor property types.

If a property is non-configurable, its writable attribute can only be changed to false.

A TypeError is thrown when attempts are made to change non-configurable property attributes (besides the writable attribute) unless the current and new values are the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM