Parent:
function Parent(name){ this.name=name; } Parent.prototype.sayHello=function(){ console.log("Hello,"+this.name); }
Prototype chain inheritance
function Kid(){}; Kid.prototype=new Parent("who"); var k=new Kid(); console.log(k.name); //who console.log(k.sayHello()); //Hello,who
Disadvantages:Unable to pass parameters to the parent when creating an instance
function Kid(name){ Parent.call(this,name); }; var k=new Kid("who"); console.log(k.name); //who console.log(k.sayHello()); //error
Disadvantages:Unable to obtain parent prototype chain attributes
function Kid(name){ var p=new Parent(name); return p; }; var k=new Kid("who"); console.log(k.name); //who console.log(k.sayHello()); //Hello,who
Disadvantages: The instance is the instance of the parent
function Kid(name){ var p=new Parent(name); for(var item in p){ Kid.prototype[item]=p[item]; } } var k=new Kid("who"); console.log(k.name); //who console.log(k.sayHello()); //Hello,who
Disadvantages: Taking up too much memory
function Kid(name){ Parent.call(this,name); } Kid.prototype=new Parent(); var k=new Kid("who"); console.log(k.name); //who console.log(k.sayHello()); //Hello,who
Disadvantages: The parent class constructor is called twice
function Kid(name){ Parent.call(this,name); } (function(){ var p=function(){}; p.prototype=Parent.prototype; Kid.prototype=new p(); })()
Disadvantages: The writing method is more cumbersome
The above is the detailed content of Introduction to several methods of prototypal inheritance. For more information, please follow other related articles on the PHP Chinese website!