4.1 继承 – 就这么简单
继承是面向对象编程(OOP)中的一个基本概念,它允许一个类(称为子类或子类)继承另一个类的字段和方法 (称为父类或超类)。
这种方法允许创建更通用的类并重复使用代码,提高代码的组织性和可维护性。
为什么需要继承?
假设你需要编写一些代码,你决定以类的形式来实现它。后来你发现你的项目中已经有一个类,它几乎可以 完成你所需的一切。你可以简单地复制这个类的代码到你的类中,尽情享用。
或者,你可以“好像复制一样”。你可以声明那个类是你的类的父类,那么JavaScript将为你的类添加父类的行为。
想象一下,你是大自然,你想创造一只狗。哪种方式更快:用细菌创造一只狗要花十亿年,还是在20万年内驯化一匹狼?
4.2 通过原型的继承概念
JavaScript中的原型继承 是一种允许对象继承其他对象的属性和方法的基本机制。这允许创建复杂的对象层次结构并重用代码。
在JavaScript中,每个对象都有一个隐藏属性[[Prototype]],指向其原型。原型用于实现继承,这使得对象可以从其他对象继承属性和方法。
简单继承的例子
步骤1:创建基础对象
const animal = {
eat() {
console.log('Eating...');
},
sleep() {
console.log('Sleeping...');
}
};
步骤2:创建继承对象
const dog = Object.create(animal);
dog.bark = function() {
console.log('Barking...');
};
步骤3:使用继承的属性和方法
dog.eat(); // 输出: Eating...
dog.sleep(); // 输出: Sleeping...
dog.bark(); // 输出: Barking...
在这个例子中,对象 dog
继承了对象 animal
的方法 eat()
和 sleep()
,并添加了自己的方法 bark()
。
4.3 通过原型的深层继承
原型链
在JavaScript中,继承可以更加复杂,对象可以相互继承,形成原型链。
原型链的例子
在这个例子中,对象 dog
继承自 mammal
,而 mammal
又继承自 animal
。
这创建了一个原型链,使得 dog
可以访问 mammal
和 animal
的所有方法。
const animal = {
eat() {
console.log('Eating...');
}
};
const mammal = Object.create(animal);
mammal.walk = function() {
console.log('Walking...');
};
const dog = Object.create(mammal);
dog.bark = function() {
console.log('Barking...');
};
dog.eat(); // 输出: Eating...
dog.walk(); // 输出: Walking...
dog.bark(); // 输出: Barking...
检查原型链
方法 isPrototypeOf()
可以检查一个对象是否为另一个对象的原型。
例子:
console.log(animal.isPrototypeOf(mammal)); // 输出: true
console.log(mammal.isPrototypeOf(dog)); // 输出: true
console.log(animal.isPrototypeOf(dog)); // 输出: true
4.4 覆盖方法
通过原型继承不仅可以添加新方法,还可以覆盖现有方法。
覆盖方法的例子
在这个例子中,对象 dog
的方法 speak()
覆盖了对象 animal
的方法 speak()
:
const animal = {
speak() {
console.log('Animal speaks');
}
};
const dog = Object.create(animal);
dog.speak = function() {
console.log('Dog barks');
};
animal.speak(); // 输出: Animal speaks
dog.speak(); // 输出: Dog barks
调用父对象的方法
为了在JavaScript中调用父对象的方法,可以使用 call()
或 apply()
方法。
例子:
const animal = {
speak() {
console.log('Animal speaks');
}
};
const dog = Object.create(animal);
dog.speak = function() {
animal.speak.call(this);
console.log('Dog barks');
};
dog.speak();
// 输出:
// Animal speaks
// Dog barks
4.5 深入使用原型继承
扩展内置对象
你可以通过向它们的原型添加方法来扩展JavaScript的内置对象。
例子:
Array.prototype.sum = function() {
return this.reduce((acc, value) => acc + value, 0);
};
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.sum()); // 输出: 15
创建多层次的层次结构
您可以使用原型继承创建更复杂的多层次对象层次结构。
例子:
const livingBeing = {
breathe() {
console.log('Breathing...');
}
};
const animal = Object.create(livingBeing);
animal.eat = function() {
console.log('Eating...');
};
const mammal = Object.create(animal);
mammal.walk = function() {
console.log('Walking...');
};
const dog = Object.create(mammal);
dog.bark = function() {
console.log('Barking...');
};
dog.breathe(); // 输出: Breathing...
dog.eat(); // 输出: Eating...
dog.walk(); // 输出: Walking...
dog.bark(); // 输出: Barking...
GO TO FULL VERSION