在JavaScript中,继承和多态是面向对象编程(OOP)的核心概念。
继承(Inheritance)
继承允许我们创建一个基于另一个类的新类,新类继承或扩展了原有类的属性和方法。在JavaScript中,继承通常通过原型链(Prototype Chain)实现。
1. 原型链继承
这是最简单的继承方式,通过设置构造函数的prototype
属性来实现。
function Parent() {
this.parentProperty = true;
}
Parent.prototype.getParentProperty = function() {
return this.parentProperty;
};
function Child() {
this.childProperty = false;
}
// 继承Parent
Child.prototype = new Parent();
// 新增或覆盖方法
Child.prototype.getChildProperty = function() {
return this.childProperty;
};
var childInstance = new Child();
console.log(childInstance.getParentProperty()); // 输出 true
console.log(childInstance.getChildProperty()); // 输出 false
2. 构造函数继承
通过在子类构造函数中调用父类构造函数来实现。
function Parent(name) {
this.name = name;
this.colors = ['red', 'blue', 'green'];
}
function Child(name) {
Parent.call(this, name); // 调用Parent构造函数并绑定this
}
var child1 = new Child('child1');
child1.colors.push('yellow');
console.log(child1.name); // 输出 'child1'
console.log(child1.colors); // 输出 ['red', 'blue', 'green', 'yellow']
var child2 = new Child('child2');
console.log(child2.name); // 输出 'child2'
console.log(child2.colors); // 输出 ['red', 'blue', 'green'],不受child1影响
3. 组合继承(原型链 + 构造函数)
结合了原型链和构造函数的优点。
function Parent(name) {
this.name = name;
this.colors = ['red', 'blue', 'green'];
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child(name, age) {
Parent.call(this, name); // 构造函数继承
this.age = age;
}
Child.prototype = new Parent(); // 原型链继承
Child.prototype.constructor = Child;
Child.prototype.sayAge = function() {
console.log(this.age);
};
var child = new Child('child', 18);
child.sayName(); // 输出 'child'
child.sayAge(); // 输出 18
多态(Polymorphism)
多态指的是同一个行为具有多个不同表现形式或形态的能力。在JavaScript中,多态通常通过继承和重写方法来实现。
function Animal() {}
Animal.prototype.speak = function() {
console.log('Some sound');
};
function Dog() {}
Dog.prototype = new Animal();
Dog.prototype.speak = function() {
console.log('Woof!');
};
function Cat() {}
Cat.prototype = new Animal();
Cat.prototype.speak = function() {
console.log('Meow!');
};
// 多态性的体现
function makeSound(animal) {
animal.speak();
}
var dog = new Dog();
var cat = new Cat();
makeSound(dog); // 输出 'Woof!'
makeSound(cat); // 输出 'Meow!'
在这个例子中,makeSound
函数接受一个Animal
类型的对象,并调用它的speak
方法。由于Dog
和Cat
都继承自Animal
,并且它们都重写了speak
方法,所以当传入不同的对象时,makeSound
函数会表现出不同的行为,这就是多态的体现。
通过继承和多态,JavaScript允许我们创建可重用和可扩展的代码,这也是面向对象编程的核心优势之一