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

Ben*_*Ben 3 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
Run Code Online (Sandbox Code Playgroud)

Ole*_*leg 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'); };
Run Code Online (Sandbox Code Playgroud)

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

吸气剂仍在这里
xxx