Home > Web Front-end > JS Tutorial > body text

Introduction to several methods of prototypal inheritance

一个新手
Release: 2017-10-16 09:16:46
Original
1340 people have browsed it

Prototype inheritance

Parent:

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

    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
    Copy after login

    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
    Copy after login

    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
    Copy after login

    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
    Copy after login

    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();
    })()
    Copy after login

    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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!