JavaScript get/set methods vs. standard methods

2020-05-19 02:45发布

问题:

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?

回答1:

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.