在 JavaScript 中,可以使用类来实现继承和多态。下面是一些基本的概念和示例:
1.类的继承
JavaScript 中的类继承可以通过 extends 关键字来实现。子类可以继承父类的属性和方法,并且可以在自己的构造函数中调用父类的构造函数。
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
constructor(name) {
super(name);
}
speak() {
console.log(`${this.name} barks.`);
}
}
const d = new Dog('Mitzie');
d.speak(); // Output: "Mitzie barks."
2.多态
多态是指同一种操作作用于不同的对象上面,可以产生不同的解释和不同的执行结果。在 JavaScript 中,可以通过方法重写来实现多态。
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
constructor(name) {
super(name);
}
speak() {
console.log(`${this.name} barks.`);
}
}
class Cat extends Animal {
constructor(name) {
super(name);
}
speak() {
console.log(`${this.name} meows.`);
}
}
const animals = [new Dog('Mitzie'), new Cat('Fluffy')];
for (let animal of animals) {
animal.speak();
}
// Output:
// "Mitzie barks."
// "Fluffy meows."
3.方法
在 JavaScript 中,类的方法可以通过在类中定义函数来实现。这些方法可以在类的实例上调用。
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
get area() {
return this.width * this.height;
}
set area(value) {
this.width = value / this.height;
}
}
const rect = new Rectangle(4, 5);
console.log(rect.area); // Output: 20
rect.area = 10;
console.log(rect.width); // Output: 2
console.log(rect.height); // Output: 5