Home  >  Article  >  Web Front-end  >  Introduction to several methods of prototypal inheritance

Introduction to several methods of prototypal inheritance

一个新手
一个新手Original
2017-10-16 09:16:461317browse

Prototype inheritance

Parent:

    function Parent(name){
        this.name=name;
    }
    Parent.prototype.sayHello=function(){
        console.log("Hello,"+this.name);
    }
  1. 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

  2. ##Construction inheritance

    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

  3. Instance inheritance

    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

  4. Copy inheritance

    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

  5. Combined inheritance

    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

  6. Parasitic Combination Inheritance

    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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn