今天我们来学习一下如何在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.prototype = Object.create(Animal.prototype);
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();
|