本文介绍了JavaScript get/set方法与标准方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么JavaScript有两种获取/设置对象属性的不同方式?

Why does JavaScript have two different ways to get/set object properties?

示例:

//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?

推荐答案

与普通方法不同,使用getset可以使您直接对对象的属性进行操作(===简洁代码).幕后的getter和setter方法.

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.

这篇关于JavaScript get/set方法与标准方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 05:45