多态(Polymorphism)是面向对象编程的三大特性之一,另外两个是封装和继承。多态意味着你可以将子类的对象当作父类的对象来使用,而且在运行时会调用子类的方法。在JavaScript中,多态主要通过原型链和构造函数来实现。
通过将子类的原型设置为父类的实例,可以实现多态。
function Animal() {}
Animal.prototype.sayName = function() {
console.log('My name is Animal');
};
function Dog() {}
Dog.prototype = new Animal();
Dog.prototype.constructor = Dog;
Dog.prototype.sayName = function() {
console.log('My name is Dog');
};
function Cat() {}
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;
Cat.prototype.sayName = function() {
console.log('My name is Cat');
};
function sayName(animal) {
animal.sayName();
}
var dog = new Dog();
var cat = new Cat();
sayName(dog); // My name is Dog
sayName(cat); // My name is Cat
通过在子类构造函数中调用父类构造函数,可以实现多态。
function Animal(name) {
this.name = name;
}
Animal.prototype.sayName = function() {
console.log('My name is ' + this.name);
};
function Dog(name) {
Animal.call(this, name);
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
function Cat(name) {
Animal.call(this, name);
}
Cat.prototype = Object.create(Animal.prototype);
Cat.prototype.constructor = Cat;
function sayName(animal) {
animal.sayName();
}
var dog = new Dog('Buddy');
var cat = new Cat('Whiskers');
sayName(dog); // My name is Buddy
sayName(cat); // My name is Whiskers
Object.create
来避免这个问题。通过以上方法,可以在JavaScript中实现多态,提高代码的灵活性和可维护性。
领取专属 10元无门槛券
手把手带您无忧上云