






















function Animal(name) { this.name = name; } Animal.prototype.speak = function() { console.log(this.name + ' makes a noise'); }; function Dog(name, breed) { // 实现继承 Animal.call(this,name); this.breed=breed; } //方法1 // Dog.prototype=Object.create(Animal.prototype); // Dog.prototype.constructor=Dog; //方法二 inherit(Dog,Animal) function inherit(child,parent){ const proto=Object.create(parent.prototype); child.prototype=proto; child.prototype.constructor=child; } Dog.prototype.bark=function(){ console.log(this.name+ ' barks') } // 实现 Dog 继承 Animal,并添加 bark 方法 const dog = new Dog('Buddy', 'Golden'); dog.speak(); // Buddy makes a noise dog.bark(); // Buddy barks! console.log(dog instanceof Dog); // true console.log(dog instanceof Animal); // true
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。