0%

javascript-prototype-inheritance

今天我们来学习一下如何在JavaScript中实现原型继承,话不多说,直接上代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// 父类的构造函数
function Animal(name) {
this.name = name;
}

// 父类的方法
Animal.prototype.printName = function () {
console.log(this.name);
};

// 子类构造函数
function Dog(name, category) {
// 好用父类构造函数,初始化父类属性。
Animal.call(this, name);

// 初始化子类的属性
this.category = category;
}

// 设置 Dog 的原型为 Animal 的实例,建立原型链
Dog.prototype = Object.create(Animal.prototype);

// 修复子类的 constructor 指向(上面一行代码已经将constructor指向了Animal)
Dog.prototype.constructor = Dog;

// 子类独有的方法。
Dog.prototype.printCategory = function () {
console.log(`Dog name: ${this.name} barking`);
};

const dog = new Dog('dog', 'Pet');
dog.printName(); // 调用父类的方法
dog.printCategory(); // 调用自己的方法