Reputation: 816
Is there any real difference between the get
operator:
var obj = {
get prop () {
//insert code here
}
};
and using defineProperty
:
var obj;
Object.defineProperty(obj, "prop", {
get: function () {
//insert code here
}
}
The MDN pages say that compatibility is about the same.
Upvotes: 6
Views: 190
Reputation: 112867
Object.defineProperty
will default to enumerable: false
and configurable: false
, while the object literal getter syntax will default to enumerable: true
and configurable: true
. This can be verified with Object.getOwnPropertyDescriptor(obj, "prop")
.
This means that in the former case prop
will show up in for
-in
loops and Object.keys(obj)
, and doing a delete obj.prop
will fail (noisily in strict mode, silently otherwise). The opposite will be true for the latter case.
Note that Object.defineProperty
(or Object.create
or Object.defineProperties
) will allow you to separately choose the configurability and enumerability of your properties, while the object literal getter syntax will not.
Upvotes: 8