Using getter and setters versus defining properties in javascript
Apart from the coding style, are there any advantages / disadvantages:
Circle.prototype = { radius : 10};
Object.defineProperty(Circle.prototype, 'circumference', {
get: function() { return 2*Math.PI*this.radius; }
});
against
Circle.prototype = {
radius : 10,
get circumference() { return 2*Math.PI*this.radius; }
}
source to share
In a property definition, JavaScript handles it using an internal method DefineOwnProperty
, where the assignment is handled by an internal method Put
. In short, the second checks if the property is read-only, and if so, then it fails. This can have implications when using read-only properties that prevent assignment, but not .
If you want to create a new property, it is better to use a definition. If you want to change the value of a property, you can use assignment.
Look here for a more, very interesting article.
EDIT: In fact, defineProperty
used for reasons like defining read-only properties and other reasons for the behavior of a certain property. Have a look here for more .
source to share