【发布时间】:2016-07-14 06:51:38
【问题描述】:
在这样的对象中使用get 时,get 有效:
var people = {
name: "Alex",
get sayHi() {
return `Hi, ${this.name}!`
}
};
var person = people;
document.write(person.sayHi);
但是使用函数我得到一个错误。如何在这样的函数中使用 Getter 和 Setter?
function People2() {
this.name = "Mike";
get sayHi() {
return `Hi, ${this.name}!`;
}
};
var user = new People2();
document.write(user.sayHi);
【问题讨论】:
-
不确定this是否重复
-
@bergi - 我搜索过。没有找到关于如何在函数中而不是在对象中使用 Getter 和 Setter 的问题
-
@AlexeyTseitlin 你可以使用
Object.defineProperty来定义getter 和setter。您还可以将Person2封装在一个类中,即。 e.class People2 { constructor() { this.name = "Mike"; } get sayHi() { return "Hi, " + this.name;} }
标签: javascript function getter-setter