一、“getter” 和 “setter”的概念
在JavaScript中,“getter”和“setter”分别是一种函数,用于获取和设置对象的某个属性。一个 getter是一个可以读取属性的方法,它可能是一个普通函数,也可以是一个类属性(使用 get
关键字)。一个 setter是一个可以设置属性值的方法,它可能是一个普通函数,也可以是一个类属性(使用 set
关键字)。
二、getter/setter在编程中的应用
在编程中,我们通常使用getter和setter方法来控制对象属性的访问。下面的示例代码演示了如何使用getter和setter:
class Person {
constructor(name) {
this._name = name;
}
get name() {
return this._name;
}
set name(name) {
this._name = name;
}
}
let person = new Person('Alice');
console.log(person.name); // Alice
person.name = 'Bob';
console.log(person.name); // Bob
在上面的代码中,我们创建了一个Person对象,并为name属性添加一个getter和setter。当获取name属性时,getter方法将返回_name
变量的值;当设置name属性的值时,setter方法将更改_name
变量的值。通过使用getter和setter,我们可以控制对象属性的访问。在这个例子中,我们可以检查和限制私有变量_name
的值。
三、getter/setter在面向对象编程中的应用
在面向对象编程(OOP)中,getter和setter常常用于控制对象属性的访问,以保证对象的封装性。 以下是面向对象编程中使用getter和setter的一个简单示例:
class Rectangle {
constructor(width, height) {
this._width = width;
this._height = height;
}
get area() {
return this._width * this._height;
}
get width() {
return this._width;
}
set width(width) {
this._width = width;
}
get height() {
return this._height;
}
set height(height) {
this._height = height;
}
}
let rectangle = new Rectangle(10, 20);
console.log(rectangle.area); // 200
rectangle.width = 5;
console.log(rectangle.area); // 100
rectangle.height = 5;
console.log(rectangle.area); // 25
在上面的代码中,我们创建了一个Rectangle对象,并为width和height属性添加getter和setter。我们还添加了一个计算矩形面积的area getter。通过使用这些getter和setter,我们可以确保矩形的宽度和高度始终保持在正确的范围内,并且可以轻松计算矩形的面积。
四、使用getter和setter的注意事项
在使用getter和setter时,请注意以下几点:
1、getter和setter方法必须有不同的名称
getter和setter方法必须与属性具有不同的名称。如果方法和属性具有相同的名称,将导致递归陷阱。
2、getter和setter方法可以是计算属性
getter和setter方法可以是计算属性。这意味着getter和setter方法不需要访问任何实例变量或类变量,而是可以计算结果并返回或设置值。
3、getter和setter方法可以是静态方法
getter和setter方法可以是静态方法,可以使用类名直接调用。这允许我们在没有实例的情况下访问和更改静态变量。
五、总结
通过本文,我们深入探索了getter和setter的概念及其在编程中的应用。getter和setter既提高了对象属性的访问灵活性,又保障了对象的封装性。 完整代码如下:
class Person {
constructor(name) {
this._name = name;
}
get name() {
return this._name;
}
set name(name) {
this._name = name;
}
}
let person = new Person('Alice');
console.log(person.name); // Alice
person.name = 'Bob';
console.log(person.name); // Bob
class Rectangle {
constructor(width, height) {
this._width = width;
this._height = height;
}
get area() {
return this._width * this._height;
}
get width() {
return this._width;
}
set width(width) {
this._width = width;
}
get height() {
return this._height;
}
set height(height) {
this._height = height;
}
}
let rectangle = new Rectangle(10, 20);
console.log(rectangle.area); // 200
rectangle.width = 5;
console.log(rectangle.area); // 100
rectangle.height = 5;
console.log(rectangle.area); // 25