6 methods of--javascript inheritance for interview programming

Source: Internet
Author: User
Tags shallow copy

6 ways that JavaScript inherits

1,原型链继承2,借用构造函数继承3,组合继承(原型+借用构造)4,原型式继承5,寄生式继承6,寄生组合式继承

1. prototype chain inheritance.

<script type= "Text/javascript" >functionPerson (name,sex) { This. name=name;  This. sex=sex;  This. friends=[' John Doe '];  This. getname=function() {alert ( This. Name); }} Person.prototype.id=1; functionBoy (age) { This. age=Age ;  This. getage=function() {alert ( This. Age); }    }    //InheritanceBoy.prototype=NewPerson ("Zhang San", "male"); varboy=NewBoy (16);              alert (boy.name); //Zhang SanBoy.getage ();// -alert (boy.id);//1    //attribute Sharing issuesConsole.log (Boy.friends);//John Doe    varBoy2=NewBoy (17); Boy2.friends.push (' Harry ');//Modifying the Friends property of Boy2 also affects the properties of the boyConsole.log (boy.friends); //John Doe Harry    //Verify that you can use instanceof and isprototypeofConsole.log (Boyinstanceofperson);//trueConsole.log (Person.prototype.isPrototypeOf (boy));//true</script>

Features: Inherits the template of the parent class and inherits the prototype object of the parent class.

Disadvantage: You can only set some parameters in the parent class, the subclass cannot be flexible, does not conform to the object-oriented idea, the property that contains the reference type value will always share the corresponding value.

2. Borrowing constructor inheritance

<script type= "Text/javascript" >//Parent Class    functionPerson (name,sex) { This. name=name;  This. sex=sex;  This. friends=[' John Doe ']; } Person.prototype.id=1; //sub-class    functionBoy (name,sex,age) {//borrowingPerson.call ( This, Name,age);  This. age=Age ;  This. getage=function() {alert ( This. Age); }    }    varboy=NewBoy ("Zhang San", "male", 16);  alert (boy.name); //Zhang SanBoy.getage (); // -alert (boy.id); //undefined does not inherit a prototype object from a parent class    //Property Sharing Issue ———— There is no sharing      //Verify that you can use instanceof and isprototypeofConsole.log (Boyinstanceofperson);//falseConsole.log (Person.prototype.isPrototypeOf (boy));//false</script>

Feature: Inherits only the template of the parent class, does not inherit the parent class's prototype object.

Cons: methods are defined in constructors and cannot be reused.

3. The most common inheritance pattern for combinatorial inheritance (prototype + borrowing constructs)

<script type= "Text/javascript" >//Parent Class    functionPerson (name,sex) { This. name=name;  This. sex=sex; } Person.prototype.id=1; //sub-class    functionBoy (name,sex,age) {//to inherit a template from a parent class by borrowing a constructorPerson.call ( This, Name,age);  This. age=Age ;  This. getage=function() {alert ( This. Age); }    }        //do not pass parameters, inherit the template of the parent class, inherit the prototype object ID of the parent classBoy.prototype=NewPerson (); varboy=NewBoy ("Zhang San", "male", 16);  alert (boy.name); //Zhang SanBoy.getage (); // -alert (boy.id); //1    //Property Sharing Issues ———— there is no sharing except for the prototype object of the parent class      //Verify that you can use instanceof and isprototypeofConsole.log (Boyinstanceofperson);//trueConsole.log (Person.prototype.isPrototypeOf (boy));//true</script>

Features: Inherits the template of the parent class and inherits the prototype object of the parent class.

Cons: Do 3 things, inherit the parent class two times template, inherit a prototype object

Prototype inheritance solves this problem.

4. prototype-Type Inheritance

<script type= "Text/javascript" >varperson={name:' Zhang San ', Sex:Male, friends:[' John Doe ']    }    functionObject (obj) {functionF () {}//Create an empty constructorF.prototype=obj;//use the incoming object as a prototype for this constructor        return NewF ();//returns a new instance with a shallow copy of the incoming object    }    varboy=object (person); //ECMAScript 5 New Object.create () method behaves the same as this example of the object method    //can be changed to object.create (person);alert (boy.name); //Zhang San    //But there is also the problem of attribute sharing in the prototype type.    //For example:    varGirl=object (person); Girl.friends.push (' Harry '); alert (boy.friends); //John Doe Harryalert (girl.friends);//John Doe Harry    //Modify the Friends property in Girl Boy will also be affected         //Unable to use instanceof and isprototypeof</script>

The purpose of creation is to create new objects based on existing objects, without having to create custom types.

Properties that contain reference type values will always share the corresponding values, just as you would with a prototype pattern.

5. Parasitic inheritance

<script type= "Text/javascript" >functionObject (obj) {functionF () {}//Create an empty constructorF.prototype=obj;//use the incoming object as a prototype for this constructor        return NewF ();//returns a new instance with a shallow copy of the incoming object    }    functionPerson (person) {varClone=object (person); Clone.getsex=function() {alert ( This. Sex); }        returnclone; }    varperson={name:' Zhang San ', Sex:Male, friends:[' John Doe ']    }    varboy=Person (person);         Boy.getsex (); //male    //attribute sharing problem ———— because of the same instance, there is a sharing issue      varBoy2=Person (person); Boy2.friends.push (' Harry ');     alert (boy.friends); //John Doe Harry        //Verify that you can use instanceof and isprototypeofConsole.log (Boyinstanceofperson);//falseConsole.log (Person.prototype.isPrototypeOf (boy));//false</script>

Similar to the constructor pattern, the inability to reuse functions reduces efficiency.

6. Parasitic combined inheritance

<script type= "Text/javascript" >functionObject (o) {functionF () {} console.log (o); F.prototype=o; return NewF (); }    functionExtend (subtype,supertype) {varPrototype=object (Supertype.prototype);//Create a copy of the parent classPrototype.constructor=subtype;//add a missing default constructor for the created replicaSubtype.prototype=prototype;//To assign a newly created object to a prototype of a subclass    }    functionPerson (name) { This. name=name;  This. friends=[' John Doe ']; }    functionBoy (Name,sex) {Person.call ( This, name);//to inherit a template from a parent class by borrowing a constructor         This. sex=sex;  } extend (Boy,person); //Inheritance    varboy=NewBoy (' Zhang San ', ' man '));     alert (boy.name); //Zhang San    //Property Sharing Issues ———— There is no sharing issue      varBoy2=NewBoy (' Zhang San ', ' man ')); Boy2.friends.push (' Harry ');     alert (boy.friends); //John Doe    //Verify that you can use instanceof and isprototypeofConsole.log (Boyinstanceofperson);//falseConsole.log (Person.prototype.isPrototypeOf (boy));//false</script>

Parasitic combination inheritance resolves that composite inheritance calls a two-time parent class constructor, which eventually contains all the instance properties of the parent class, and the properties of the parent class are not required, and the properties of the child class override the properties of the parent class.

Parasitic combination inheritance calls only once the parent class constructor, the prototype chain can remain unchanged, so also can use instanceof and isprototypeof (), Yui's Extend method is the use of parasitic combination inheritance, is to implement type-based inheritance of the most effective way.

6 methods of--javascript inheritance for interview programming

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.