如何在Javascript对象(Class)中使用setter和getter?

Mar*_*ark 2 javascript getter setter class getter-setter

以下脚本不起作用.什么是正确的方法?

function AnObject () {
    get this.apple = () {
        return this.apple + "GET";
    }
    set this.apple = ( newValue ) {
        return newValue + "SET";
    }
}

var obj = new AnObject();
obj.apple = "Lemon";
console.log( obj.apple ); // LemonSETGET
Run Code Online (Sandbox Code Playgroud)

Poi*_*nty 5

你可以使用Object.defineProperties():

function AnObject() {
  Object.defineProperties(this, {
    apple: {
      get: function() {
        return this._apple + " GET";
      },
      set: function(value) {
        this._apple = value;
      },
      configurable: true, writable: true
    }
  });
 }
Run Code Online (Sandbox Code Playgroud)

请注意,如果要直接保持对象的值,则必须小心使用其他属性名称.如果没有,你可以使用构造函数的闭包:

function AnObject() {
  var theApple;

  Object.defineProperties(this, {
    apple: {
      get: function() {
        return theApple + " GET";
      },
      set: function(value) {
        theApple = value;
      },
      configurable: true, writable: true
    }
  });
 }
Run Code Online (Sandbox Code Playgroud)