ECMAScript 5 (ES5 2009) 引入了 Getter 和 Setters。
Getter 和 Setter 允许您定义对象存取器(计算属性)。
这个例子使用了一个lang
属性为get
的值language
属性。
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
language: "en",
get lang() {
return this.language;
}
};
// Display data from the object using a getter:
document.getElementById("demo").innerHTML = person.lang;
亲自试一试 »
这个例子使用了一个lang
属性为set
的值language
属性。
const person = {
firstName: "John",
lastName: "Doe",
language: "",
set lang(lang) {
this.language = lang;
}
};
// Set an object property using a setter:
person.lang = "en";
// Display data from the object:
document.getElementById("demo").innerHTML = person.language;
亲自试一试 »
这两个例子有什么区别?
const person = {
firstName: "John",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
// Display data from the object using a method:
document.getElementById("demo").innerHTML = person.fullName();
亲自试一试 »
const person = {
firstName: "John",
lastName: "Doe",
get fullName() {
return this.firstName + " " + this.lastName;
}
};
// Display data from the object using a getter:
document.getElementById("demo").innerHTML = person.fullName;
亲自试一试 »
示例 1 将 fullName 作为函数访问:person.fullName()。
示例 2 将 fullName 作为属性访问:person.fullName。
第二个示例提供了更简单的语法。
使用 getter 和 setter 时,JavaScript 可以确保更好的数据质量。
使用lang
在此示例中,属性返回的值language
大写的属性:
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
language: "en",
get lang() {
return this.language.toUpperCase();
}
};
// Display data from the object using a getter:
document.getElementById("demo").innerHTML = person.lang;
亲自试一试 »
使用lang
在此示例中,属性将大写值存储在language
属性:
const person = {
firstName: "John",
lastName: "Doe",
language: "",
set lang(lang) {
this.language = lang.toUpperCase();
}
};
// Set an object property using a setter:
person.lang = "en";
// Display data from the object:
document.getElementById("demo").innerHTML = person.language;
亲自试一试 »
这个Object.defineProperty()
方法也可用于添加 Getters 和 Setters:
// Define object
const obj = {counter : 0};
// Define setters and getters
Object.defineProperty(obj, "reset", {
get : function () {this.counter = 0;}
});
Object.defineProperty(obj, "increment", {
get : function () {this.counter++;}
});
Object.defineProperty(obj, "decrement", {
get : function () {this.counter--;}
});
Object.defineProperty(obj, "add", {
set : function (value) {this.counter += value;}
});
Object.defineProperty(obj, "subtract", {
set : function (value) {this.counter -= value;}
});
// Play with the counter:
obj.reset;
obj.add = 5;
obj.subtract = 1;
obj.increment;
obj.decrement;
亲自试一试 »
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!