在像这样的对象中使用 get
时,get
有效:
var people = {
name: "Alex",
get sayHi() {
return `Hi, ${this.name}!`
}
};
var person = people;
document.write(person.sayHi);
但是对于一个函数,我得到了一个错误。如何在这样的函数中使用 Getters 和 Setters?
function People2() {
this.name = "Mike";
get sayHi() {
return `Hi, ${this.name}!`;
}
};
var user = new People2();
document.write(user.sayHi);
最佳答案
您只能在类 (ES2015) 和对象文字中使用实际的 get
和 set
关键字。
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}!`;
}
}
关于javascript - 函数中的 Getters 和 Setters (javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38367348/