NL5*_*500 38 javascript getter-setter
我知道getter和setter是如何在JavaScript中工作的.我不明白为什么我们需要它们才能使用普通函数得到相同的结果?请考虑以下代码:
var person = {
firstName: 'Jimmy',
lastName: 'Smith',
get fullName() {
return this.firstName + ' ' + this.lastName;
}
}
console.log(person.fullName); // Jimmy Smith
Run Code Online (Sandbox Code Playgroud)
我们可以用一个函数轻松替换getter:
var person = {
firstName: 'Jimmy',
lastName: 'Smith',
fullName: function() {
return this.firstName + ' ' + this.lastName;
}
}
console.log(person.fullName()); // Jimmy Smith
Run Code Online (Sandbox Code Playgroud)
我没有看到写入getter和setter的重点.
Bul*_*ral 21
使用getter或setter和使用标准函数之间的区别在于,在赋值时会自动调用getter/setter.因此它看起来就像一个普通的属性,但在幕后你可以在赋值之前或之后运行额外的逻辑(或检查).
因此,如果您决定将此类额外逻辑添加到已具有引用的现有对象属性之一,则可以将其转换为getter/setter样式,而无需更改有权访问该属性的其余代码.
小智 5
// A regular function can set and get (return) a value similar to a getter and setter function
function Car() {
const fuel = 50
return {
fuel
}
}
const car = Car()
console.log(car.fuel)
>>> 50
car.fuel = 100
console.log(car.fuel)
>>> 100
// A getter function can encapuslate a property and therefore create safe code that cannot be changed.
function Car1() {
const fuel = 50
return {
get fuel() { return fuel }
}
}
const car1 = Car1()
car1.fuel = 3000
console.log(car1.fuel)
>>> 50
// A setter function can further safeguard a property by imposing conditions on it that need to be met.
function Car2() {
let fuel = 50
return {
get fuel() { return fuel },
set fuel(value) {
fuel = value
if (value > 100) fuel = 100
}
}
}
const car2 = Car2()
car2.fuel = 3000
console.log(car2.fuel)
>>> 100
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7744 次 |
| 最近记录: |