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
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 article 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With