I looked around for how to use the Object.defineProperty method, but couldn\'t find anything decent.
Someone gave me this snippet of code:
Object.def
Basically, defineProperty
is a method that takes in 3 parameters - an object, a property, and a descriptor. What is happening in this particular call is the "health"
property of the player
object is getting assigned to 10 plus 15 times that player object's level.
Object.defineProperty(player, "health", {
get: function () {
return 10 + ( player.level * 15 );
}
});
Object.defineProperty
is used in order to make a new property on the player object. Object.defineProperty
is a function which is natively present in the JS runtime environemnt and takes the following arguments:
Object.defineProperty(obj, prop, descriptor)
The descriptor object is the interesting part. In here we can define the following things:
<boolean>
: If true
the property descriptor may be changed and the property may be deleted from the object. If configurable is false
the descriptor properties which are passed in Object.defineProperty
cannot be changed.<boolean>
: If true
the property may be overwritten using the assignment operator.<boolean>
: If true
the property can be iterated over in a for...in
loop. Also when using the Object.keys
function the key will be present. If the property is false
they will not be iterated over using a for..in
loop and not show up when using Object.keys
.<function>
: A function which is called whenever is the property is required. Instead of giving the direct value this function is called and the returned value is given as the value of the property<function>
: A function which is called whenever is the property is assigned. Instead of setting the direct value this function is called and the returned value is used to set the value of the property.const player = {
level: 10
};
Object.defineProperty(player, "health", {
configurable: true,
enumerable: false,
get: function() {
console.log('Inside the get function');
return 10 + (player.level * 15);
}
});
console.log(player.health);
// the get function is called and the return value is returned as a value
for (let prop in player) {
console.log(prop);
// only prop is logged here, health is not logged because is not an iterable property.
// This is because we set the enumerable to false when defining the property
}
yes no more function extending for setup setter & getter this is my example Object.defineProperty(obj,name,func)
var obj = {};
['data', 'name'].forEach(function(name) {
Object.defineProperty(obj, name, {
get : function() {
return 'setter & getter';
}
});
});
console.log(obj.data);
console.log(obj.name);
Object.defineProperty() is a global function..Its not available inside the function which declares the object otherwise.You'll have to use it statically...