JavaScript高级程序设计-封装类
在JavaScript中,我们可以通过封装类来实现面向对象编程。封装类是一种将数据和方法封装在一起的方式,它可以帮助我们更好地管理代码,并提供更高的灵活性和可重用性。
类和对象
在JavaScript中,类是一种创建对象的模板,而对象是类的一个实例。类定义了对象的属性和方法,我们可以通过创建对象来使用这些属性和方法。
下面是一个简单的示例,展示了如何定义一个类和创建一个对象:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
let person = new Person("Alice", 25);
person.sayHello(); // 输出:Hello, my name is Alice and I am 25 years old.
在上面的代码中,我们定义了一个名为Person的类,它有两个属性:name和age。我们还定义了一个方法sayHello,它将打印出对象的名称和年龄。
我们使用new
关键字来创建一个Person对象,并将其存储在一个变量中。然后,我们调用对象的sayHello方法,并输出结果。
封装和访问控制
封装是面向对象编程的关键概念之一,它允许我们控制对象内部的数据和方法的访问权限。在JavaScript中,我们可以使用_
来表示私有属性和方法,以及get
和set
关键字来定义公共的访问方法。
下面是一个示例,展示了如何使用封装和访问控制:
class Rectangle {
constructor(width, height) {
this._width = width;
this._height = height;
}
get width() {
return this._width;
}
set width(value) {
if (value > 0) {
this._width = value;
}
}
get height() {
return this._height;
}
set height(value) {
if (value > 0) {
this._height = value;
}
}
get area() {
return this._width * this._height;
}
}
let rectangle = new Rectangle(10, 5);
console.log(rectangle.width); // 输出:10
console.log(rectangle.height); // 输出:5
console.log(rectangle.area); // 输出:50
rectangle.width = 20;
rectangle.height = 10;
console.log(rectangle.area); // 输出:200
在上面的代码中,我们定义了一个名为Rectangle的类,它有两个私有属性:width和height。我们使用get
和set
关键字来定义了宽度和高度的访问方法,以及一个计算面积的访问方法。
我们创建了一个Rectangle对象,并使用访问方法来获取和设置宽度和高度。然后,我们计算并输出矩形的面积。
继承和多态
继承是面向对象编程的另一个重要概念,它允许我们创建一个新类,并从现有类继承属性和方法。多态是指子类可以覆盖父类的方法,并实现自己的行为。
下面是一个示例,展示了如何使用继承和多态:
class Shape {
constructor(color) {
this._color = color;
}
get color() {
return this._color;
}
draw() {
console.log("Drawing a shape");
}
}
class Circle extends Shape {
constructor(color, radius) {
super(color);
this._radius = radius;
}
get radius() {
return this._radius;
}
draw() {
console.log(`Drawing a circle with radius ${this._radius}`);
}
}
let shape = new Shape("red");
console.log(shape.color); // 输出:red
shape.draw(); // 输出:Drawing a shape
let circle = new Circle("blue", 10);
console.log(circle.color); // 输出:blue
console.log(circle.radius); // 输出:10
circle.draw(); // 输出:Drawing a circle with radius 10
在上面的代码中,我们定义了一个名为Shape的基类,它有一个私有属性color和一个draw方法。然后,我们定义了一个名为Circle的子类,