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

时间:2022-09-24 22:52:03

The following script DOES NOT WORK. What would be the proper way?

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

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

4 个解决方案

#1


You can use Object.defineProperties():

您可以使用Object.defineProperties():

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

Note that you have to be careful to use a different property name if you want to keep the value around with the object directly. If not, you could use the constructor's closure:

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

function AnObject() {
  var theApple;

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

#2


To add to Pointy's ...point,

添加到Pointy的...点,

You can use getters and setters as a language feature, by putting them inside of Object Literals.

您可以将getter和setter用作语言功能,方法是将它们放在Object Literals中。

Your original constructor could be turned into a factory, with instance-based getters and setters simply by doing the following:

您可以将原始构造函数转换为工厂,只需执行以下操作即可使用基于实例的getter和setter:

function makeAnObject () {
    var hiddenApple = "Granny Smith";
    return {
      get apple () { return hiddenApple; },
      set apple (ignore) { return hiddenApple; }
    };
}

var thing = makeAnObject();
thing.apple;
thing.apple = "Crab Apple";

Keep in mind that depending on getters/setters will flat-out explode on older browsers (IE8 being the real stickler here), used this way.

请记住,取决于getter / setter将在旧版浏览器上爆炸(IE8是真正的粘合剂),以这种方式使用。

Also, using them inside of defineProperties is fine for preventing IE8 from exploding (as it's no longer a language construct)... ...buuuut, it doesn't actually add getters/setters, either (even with polyfills to add the method to Object, and not just DOM Elements), and thus, will have bugged behaviour, either due to syntax explosions, or due to doing something completely different from your other browsers.

另外,在defineProperties中使用它们可以防止IE8爆炸(因为它不再是语言结构)...... buuuut,它实际上并没有添加getter / setter(即使使用polyfill来添加方法)对象,而不仅仅是DOM元素),因此,由于语法爆炸,或者由于与您的其他浏览器完全不同,会产生错误行为。

This might not apply to you right now, and hopefully it never does... ...some of us still live in that horrible reality.

这可能现在不适用于你,希望它永远不会......我们中的一些人仍然生活在那个可怕的现实中。

#3


class User {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }


  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }


  set fullName(newValue) {
    [this.firstName, this.lastName] = newValue.split(' ');
  }



};

let user = new User("AAAA", "BBBB");
alert( user.fullName ); 
user.fullName = "CCCC DDDD";
alert( user.fullName ); 

#4


There are no setters and getters in JS

JS中没有setter和getter

But you can emulate them

但你可以效仿它们

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

var obj = new AnObject();
obj.set("Lemon");
console.log( obj.get() ); // LemonSETGET

#1


You can use Object.defineProperties():

您可以使用Object.defineProperties():

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

Note that you have to be careful to use a different property name if you want to keep the value around with the object directly. If not, you could use the constructor's closure:

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

function AnObject() {
  var theApple;

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

#2


To add to Pointy's ...point,

添加到Pointy的...点,

You can use getters and setters as a language feature, by putting them inside of Object Literals.

您可以将getter和setter用作语言功能,方法是将它们放在Object Literals中。

Your original constructor could be turned into a factory, with instance-based getters and setters simply by doing the following:

您可以将原始构造函数转换为工厂,只需执行以下操作即可使用基于实例的getter和setter:

function makeAnObject () {
    var hiddenApple = "Granny Smith";
    return {
      get apple () { return hiddenApple; },
      set apple (ignore) { return hiddenApple; }
    };
}

var thing = makeAnObject();
thing.apple;
thing.apple = "Crab Apple";

Keep in mind that depending on getters/setters will flat-out explode on older browsers (IE8 being the real stickler here), used this way.

请记住,取决于getter / setter将在旧版浏览器上爆炸(IE8是真正的粘合剂),以这种方式使用。

Also, using them inside of defineProperties is fine for preventing IE8 from exploding (as it's no longer a language construct)... ...buuuut, it doesn't actually add getters/setters, either (even with polyfills to add the method to Object, and not just DOM Elements), and thus, will have bugged behaviour, either due to syntax explosions, or due to doing something completely different from your other browsers.

另外,在defineProperties中使用它们可以防止IE8爆炸(因为它不再是语言结构)...... buuuut,它实际上并没有添加getter / setter(即使使用polyfill来添加方法)对象,而不仅仅是DOM元素),因此,由于语法爆炸,或者由于与您的其他浏览器完全不同,会产生错误行为。

This might not apply to you right now, and hopefully it never does... ...some of us still live in that horrible reality.

这可能现在不适用于你,希望它永远不会......我们中的一些人仍然生活在那个可怕的现实中。

#3


class User {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }


  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }


  set fullName(newValue) {
    [this.firstName, this.lastName] = newValue.split(' ');
  }



};

let user = new User("AAAA", "BBBB");
alert( user.fullName ); 
user.fullName = "CCCC DDDD";
alert( user.fullName ); 

#4


There are no setters and getters in JS

JS中没有setter和getter

But you can emulate them

但你可以效仿它们

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

var obj = new AnObject();
obj.set("Lemon");
console.log( obj.get() ); // LemonSETGET