Monday, June 3, 2024
138
rated 0 times [  144] [ 6]  / answers: 1 / hits: 19298  / 12 Years ago, wed, april 11, 2012, 12:00:00

I'm wondering when I should use



Object.defineProperty


to create new properties for an object. I'm aware that I'm able to set things like



enumerable: false


but when do you need this really? If you just set a property like



myObject.myprop = 5;


its descriptors are all set to true, right? I'm actually more curious when you guys use that rather verbose call to .defineProperty() and for what reasons.


More From » ecmascript-5

 Answers
894

Object.defineProperty is mainly used to set properties with specific property descriptors (e.g. read-only (constants), enumerability (to not show a property in a for (.. in ..) loop, getters, setters).



use strict;
var myObj = {}; // Create object
// Set property (+descriptor)
Object.defineProperty(myObj, 'myprop', {
value: 5,
writable: false
});
console.log(myObj.myprop);// 5
myObj.myprop = 1; // In strict mode: TypeError: myObj.myprop is read-only


Example



This method extends the Object prototype with a property. Only the getter is defined, and the enumerability is set to false.



Object.defineProperty(Object.prototype, '__CLASS__', {
get: function() {
return Object.prototype.toString.call(this);
},
enumerable: false // = Default
});
Object.keys({}); // []
console.log([].__CLASS__); // [object Array]

[#86312] Tuesday, April 10, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
carolynt

Total Points: 252
Total Questions: 98
Total Answers: 109

Location: French Southern and Antarctic Lands
Member since Sat, Oct 31, 2020
4 Years ago
;