Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript get/set methods vs. standard methods

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?

like image 430
Gerald LeRoy Avatar asked Jul 17 '14 07:07

Gerald LeRoy


People also ask

What is get and set method in JavaScript?

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.

What is the difference between getter and setter in JavaScript?

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.

What is a getter method in JavaScript?

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.

What does .get do in JavaScript?

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.


1 Answers

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.

like image 87
techfoobar Avatar answered Sep 20 '22 02:09

techfoobar