JavaScript函数中的Getter和Setter

13

在像这样的对象中使用get时,get函数可以正常工作:

var people = {
  name: "Alex",
  get sayHi() {
    return `Hi, ${this.name}!`
    }
};

var person = people;

document.write(person.sayHi);
在函数中使用Getters和Setters应该怎么做?但是我在一个函数中使用它们时出错了。

TBD

function People2() {
  this.name = "Mike";
  get sayHi() {
    return `Hi, ${this.name}!`;
  }
};

var user = new People2();

document.write(user.sayHi);


不确定这个是否是重复的。 - Bergi
@bergi - 我搜索了一下,没有找到如何在函数中使用Getter和Setter而不仅仅是在对象中使用的问题。 - Alexey Tseitlin
@AlexeyTseitlin 你可以使用 Object.defineProperty 来定义 getter 和 setter。你也可以将 Person2 封装在一个类中,例如 class People2 { constructor() { this.name = "Mike"; } get sayHi() { return "Hi, " + this.name;} } - Chiru
4个回答

16

你只能在类(ES2015)和对象字面量中使用实际的 getset 关键字。

ECMAScript 5

在 ES5 中,你通常会使用Object.defineProperty来实现你想要实现的功能:

function People2() {
    this.name = "Mike";
}
Object.defineProperty(People2.prototype, "sayHi", {
    get: function() {
        return "Hi, " + this.name + "!";
    }
});

ECMAScript 2015

在ES2015中,您还可以使用类来实现所需的行为:

class People2 {
    constructor() {
        this.name = "Mike";
    }
    get sayHi() {
        return `Hi, ${this.name}!`;
    }
}

5
你可以尝试这个。

<script>
function People2(name) {
  this.name = name;  
};

People2.prototype = {
  get sayHi() {
    return `Hi, ${this.name}!`;}
};

var user = new People2('Alex');

document.write(user.sayHi);
</script>

或者这个...

<script>
function people(name) {
    this.name = name;
};

Object.defineProperty(people.prototype, 'sayHi', {
    get: function() { return `Hi, ${this.name}!`; }
});

var person = new people('Alex');

document.write(person.sayHi);
</script>


1
我们也可以将 "people.prototype" 更改为 "this" =) - Alexey Tseitlin

2

如果你想为一个函数定义一个像 name 这样的属性,并且希望有更多的控制,我们可以在函数本身上使用 Object.defineProperty,如下所示:

function people(name) {

    //this.name = name; //this can be modified freely by caller code! we don't have any control

    var _name = name; //use a private var to store input `name`
    Object.defineProperty(this, 'name', {
        get: function() { return _name; },  //we can also use `return name;` if we don't use `name` input param for other purposes in our code
        writable: false, //if we need it to be read-only
        //... other configs
    });

};

var person = new people('Alex');
console.log(person.name); //writes Alex

-1
例如,使用这个:
function People2() {
  this.name = "Mike";
  this.__defineGetter__("sayHi", function() {
    return `Hi, ${this.name}!`;
  });
};

3
Object.prototype.__defineGetter__ 已被弃用且不是标准的。请勿使用它 - Chiru

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接