开始
例如,在 JavaScript 中,如果你想在返回对象之前获取运行某些操作的对象的属性,你会怎么做?举个例子。
var person = {
firstName: 'Amit',
lastName: 'Merchant',
fullName: function() {
return this.firstName + ' ' + this.lastName;
}
}
console.log(person.fullName()); //
为了获得由 person 对象的两个属性 firstName 和 lastName 组合而成的全名,您可以定义一个名为 fullName 的函数并运行必要的操作并返回结果。类似地,为了给属性赋值,您可以定义一个名为 setFirstName 的函数,将所需的值作为参数传递给它
var person = {
firstName: 'Amit',
lastName: 'Merchant',
fullName: function() {
return this.firstName + ' ' + this.lastName;
},
setFirstName: function(name) {
this.firstName = name;
}
}
person.setFirstName('Jon')
console.log(person.fullName()); // Jon Merchant
这里有一种在 ES6 中实现上述目标的更清晰简洁的方法。它们被称为getter和setter。
“getter”和“setter”?
getter
他是一个函数,它通过 get 关键字绑定到一个对象属性,该属性将在查找该属性时自动调用。让我们使用 getter 重写上面的例子。
var person = {
firstName: 'Amit',
lastName: 'Merchant',
get fullName() {
return this.firstName + ' ' + this.lastName;
}
}
console.log(person.fullName); // Amit Merchant
如您所见, fullName 仍然看起来像一个普通函数,但现在它是一个 getter,可以像访问对象属性一样访问它。更干净优雅,对吧?当您想在每次请求属性时都运行一些代码时,getter 很有用。
在使用 getter 时,需要考虑:
- 它可以有一个标识符,可以是数字或字符串。
- 它的参数必须正好为零。
- 它不得与另一个
get或同一属性的数据条目一起出现在对象字面量中(禁止使用{ get x() { }, get x() { } }和{ x: ..., get x() { } })。
Setters
与 getter 类似,setter 是一个函数,它通过 get 关键字绑定到对象属性,当尝试设置该属性时将调用该属性。这是一个相同的例子。
var person = {
_firstName: 'Amit',
lastName: 'Merchant',
get fullName() {
return this._firstName + ' ' + this.lastName;
},
set firstName(name) {
this._firstName = name;
}
}
person.firstName = 'Jon';
console.log(person.fullName); // Jon Merchant
每当尝试更改指定的属性时,Setter 可用于执行函数。 Setter 最常与 getter 结合使用以创建一种伪属性。不可能在一个属性上同时拥有一个包含实际值的 setter,这就是我在上面的示例中将属性名称更改为 _firstName 的原因。如果你打算这样做,你会得到这个奇怪的错误: Uncaught RangeError: Maximum call stack size exceeded 。
可以使用 delete 关键字删除设置器。
delete person.firstName;
在 setter 中使用计算属性
您可以使用 [] 在 setter 中分配计算属性名称。
var expr = 'foo';
var obj = {
baz: 'bar',
set [expr](v) { this.baz = v; }
};
console.log(obj.baz); // "bar"
obj.foo = 'baz'; // run the setter
console.log(obj.baz); // "baz"
全文完
谢谢!
开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 22 天