JavaScript get/set methods vs. standard methods

霸气de小男生 提交于 2019-12-03 03:53:22

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!