Why does JavaScript have two different ways to get/set object properties?
Example:
//implementation 1
var obj1 = {
"x":1,
get number() {return this.x},
set number(n) {this.x = n}
}
//implementation 2
var obj2 = {
"x":1,
getX: function(){return this.x},
setX: function(n){this.x = n}
}
Does one implementation style have advantages over the other?
In JavaScript, accessor properties are methods that get or set the value of an object. For that, we use these two keywords: get - to define a getter method to get the property value. set - to define a setter method to set the property value.
Getters and setters allow us to define Object Accessors. The difference between them is that the former is used to get the property from the object whereas the latter is used to set a property in an object.
Getters give you a way to define a property of an object, but they do not calculate the property's value until it is accessed. A getter defers the cost of calculating the value until the value is needed.
get() method in JavaScript is used to allow users to get the property from an object as a function. This method always returns the value of the property.
Unlike normal methods, using get
and set
lets you operate on the object's properties directly (=== cleaner/lesser code) - while actually invoking the getter and setter methods behind-the-scenes.
var obj1 = {
"x":1,
get number() {console.log('get was called'); return this.x},
set number(n) {console.log('set was called'); this.x = n}
};
alert(obj1.number); // calls the getter (and prints to console)
obj1.number = 10; // calls the setter (and prints to console)
As the other answer mentioned, decide for/against using this depending on your target browser set.
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