getter和setter只能在ES5中使用原始值吗?

时间:2015-02-25 17:03:31

标签: javascript

getter和setter是否仅适用于ES5中的原始值?

var foo = { 
  get bar() {
    return this._bar;
  },
  set bar(value) {
    this._bar = value;
  } 
}

foo.bar = function() {}; //appears to overwrite the property rather than assign the value of _bar

1 个答案:

答案 0 :(得分:6)

是什么让你认为它会覆盖财产?

var foo = { 
  get bar() {
    console.log('the getter is still here');
    return this._bar;
  },
  set bar(value) {
    this._bar = value;
  } 
}

foo.bar = function() { console.log('xxx'); };

运行foo.bar()时输出为:

  吸气剂还在这里   XXX