JavaScript Inheritance Basics (prototype chain, borrowed constructor, mixed mode, prototype inheritance, parasitic inheritance, parasitic modular inheritance) _javascript skills

Source: Internet
Author: User
Tags inheritance

Agreed to explain the JavaScript inheritance, but delayed to now explain. No more nonsense, go straight to the point.

Since you want to understand the inheritance, prove that you have a certain understanding of JavaScript-oriented objects, such as what you do not understand can refer to the object-oriented JS Basic explanation, Factory mode, constructor mode, prototype mode, mixed mode, dynamic prototype mode, The next step is to finish the JavaScript inheritance in general by those methods.

  Prototype chain

The easiest way to implement inheritance in JavaScript is to use a prototype chain to point the subtype's prototype to an instance of the parent type, which is "subtype. prototype = new parent type ();", implemented as follows:

//create constructor function for parent type supertype () {this.name = [' Wuyuchang ', ' Jack ', ' Tim '];
This.property = true;

///Add Method SuperType.prototype.getSuerperValue = function () {return This.property} for the parent type
  Create constructors for subtypes function subtype () {this.test = [' H1 ', ' H2 ', ' H3 ', ' H4 '];
This.subproperty = false;

///implementation of the critical step of inheritance, the subtype of the stereotype points to the instance of the parent type Subtype.prototype = new supertype (); 


Add a method here to the subtype, and make sure that after the inheritance is implemented, the method is empty SubType.prototype.getSubValue = function () {return this.subproperty} if the pointer points to an instance of the parent type.
/* The following is the test code example * * var Instance1 = new subtype ();
Instance1.name.push (' WYC ');
Instance1.test.push (' h5 ');    Alert (Instance1.getsuerpervalue ());      True alert (Instance1.getsubvalue ());          False alert (instance1.name);          WUYUCHANG,JACK,TIM,WYC alert (instance1.test);
H1,H2,H3,H4,H5 var instance2 = new subtype ();          alert (instance2.name);          WUYUCHANG,JACK,TIM,WYC alert (instance2.test); H1,h2,h3,h4 

You can see that code like this is a simple inheritance through the prototype chain, but there are some problems with the test code example. I believe I read the blog "object-oriented JS basic explanation, Factory mode, constructor mode, prototype model, mixed mode, dynamic prototype model The children's shoes must know the first problem with the prototype chain code is that the stereotype of the subtype is an instance of the parent type, which is the attribute of the parent type contained in the prototype of the subtype. This causes the stereotype properties of the reference type value to be shared by all instances . The Instance1.name.push (' WYC ') of the above code can prove the existence of this problem. The second problem with the prototype chain is that when you create an instance of a subtype, you cannot pass parameters to the superclass constructor . So we rarely use the prototype chain alone in actual development.

borrowing Constructors

In order to solve the two problems in the prototype chain, the developers began to use a technique called borrowing constructors to solve the problems in the prototype chain. The implementation of this technique is also quite simple, just call the constructor of the parent type within the constructor of the subtype. Remember that a function is simply an object that executes code in a particular environment, so you can execute the constructor by using the Apply () or call () method . The code is as follows:

Creates a constructor function Supertype (name) {this.name = name for the parent type;
  This.color = [' Pink ', ' yellow '];

  This.property = true;
  This.testfun = function () {alert (' http://tools.jb51.net/');

Add a method to the parent type SuperType.prototype.getSuerperValue = function () {return this.property;}
  Creates a constructor function subtype (name) {Supertype.call (this, name) for a subtype;
  This.test = [' H1 ', ' H2 ', ' H3 ', ' H4 '];
This.subproperty = false; To add a method to a subtype here, be sure to do so after inheriting, otherwise if you point the pointer at an instance of the parent type, the method is empty SubType.prototype.getSubValue = function () {return this.subproperty
;
/* The following is the test code example * * var Instance1 = new Subtype ([' Wuyuchang ', ' Jack ', ' Nick ']);
Instance1.name.push (' Hello ');
Instance1.test.push (' h5 ');
Instance1.color.push (' Blue ');            Instance1.testfun ();            Http://tools.jb51.net/alert (Instance1.name);    Wuyuchang,jack,nick,hello//Alert (Instance1.getsuerpervalue ());            Error Error alert (instance1.test);        H1,H2,H3,H4,H5 alert (Instance1.getsubvalue ()); False AlerT (Instance1.color);
pink,yellow,blue var instance2 = new Subtype (' WYC ');            Instance2.testfun ();            Http://tools.jb51.net/alert (Instance2.name);    WYC//Alert (Instance2.getsuerpervalue ());            Error Error alert (instance2.test);        H1,H2,H3,H4 alert (Instance2.getsubvalue ());            False alert (Instance2.color); Pink,yellow

You can see the above code neutron type subtype constructor by calling the parent type "Supertype.call" (This, name), which enables inheritance of the property, or passing arguments to the parent type when the subtype creates the instance, but the new problem comes again. You can see that I have defined a method in the constructor of the parent type: Testfun, which defines a method in the prototype of the parent type: Getsupervalue. However, it is still not possible to invoke the method Getsupervalue defined in the prototype of the parent type after instantiating the subtype , only the method of the constructor in the parent type can be invoked: Testfun. This is just like using a constructor pattern in the creation object, so that the function does not have to be reused. In view of these problems, the technique of borrowing constructors is rarely used alone.

Combinatorial Inheritance (prototype chain + borrow constructor)

As the name suggests, composite inheritance is a combination of the use of prototype chains and the advantages of borrowing constructors, a combination of a pattern. Implementation is also very simple, since it is a combination, which of course combines the advantages of two sides, that is, the prototype chain inheritance method, while the constructor inherits the property . The specific code implementation is as follows:

Creates a constructor function Supertype (name) {this.name = name for the parent type;
  This.color = [' Pink ', ' yellow '];

  This.property = true;
  This.testfun = function () {alert (' http://tools.jb51.net/');

Add a method to the parent type SuperType.prototype.getSuerperValue = function () {return this.property;}
  Creates a constructor function subtype (name) {Supertype.call (this, name) for a subtype;
  This.test = [' H1 ', ' H2 ', ' H3 ', ' H4 '];
This.subproperty = false;

} Subtype.prototype = new supertype (); 


Add a method here to the subtype, and make sure that after the inheritance is implemented, the method is empty SubType.prototype.getSubValue = function () {return this.subproperty} if the pointer points to an instance of the parent type.
/* The following is a test code example * * var Instance1 = new Subtype ([' Wuyuchang ', ' Jack ', ' Nick ']);
Instance1.name.push (' Hello ');
Instance1.test.push (' h5 ');
Instance1.color.push (' Blue ');            Instance1.testfun ();            Http://tools.jb51.net/alert (Instance1.name);      Wuyuchang,jack,nick,hello alert (Instance1.getsuerpervalue ());            True alert (instance1.test); H1,H2,H3,H4,H5 Alert (INSTANCE1.GETSUBVAlue ());            False alert (Instance1.color);
pink,yellow,blue var instance2 = new Subtype (' WYC ');            Instance2.testfun ();            Http://tools.jb51.net/alert (Instance2.name);      WYC alert (Instance2.getsuerpervalue ());            True alert (instance2.test);        H1,H2,H3,H4 alert (Instance2.getsubvalue ());            False alert (Instance2.color); Pink,yellow

The above code passes Supertype.call (this, name), inherits the properties of the parent type, and inherits the method of the parent type by Subtype.prototype = new Supertype (). The above code is very convenient to solve the prototype chain and borrow the constructor problems encountered, become the most commonly used in JavaScript instance inheritance method. However, mixed mode is not without drawbacks, you can see in the above code in the inheritance method in the actual inherited the property of the parent type, only at this time for reference types are shared, Therefore, it is not necessary to invoke the parent type's constructor within the subtype's constructor, thus inheriting the attributes of the parent type and overwriting the inherited properties of the stereotype, so that the two-time constructor is not required, but what can be done? Look at the following two modes before you resolve this issue.

Prototype inheritance

The implementation method of prototype inheritance differs from that of ordinary inheritance, and prototype inheritance does not use a strict constructor, but instead creates a new object based on an existing object without having to create a custom type. The specific code is as follows:

function Object (o) {
  function F () {}
  f.prototype = O;
  return new F ();
}

code example:

/* Prototype inheritance */
function object (o) {
  function F () {}
  f.prototype = O;
  return new F ();
}

var person = {
  name: ' Wuyuchang ',
  friends: [' wyc ', ' Nicholas ', ' Tim ']
}

var Anotherperson = object (pers ON);
Anotherperson.name = ' Greg ';
AnotherPerson.friends.push (' Bob ');

var AnotherPerson2 = object (person);
Anotherperson2.name = ' Jack ';
AnotherPerson2.friends.push (' Rose ');

alert (person.friends);  Wyc,nicholas,tim,bob,rose

Parasitic inheritance

/* Parasitic inheritance *
/function Createanother (original) {
  var clone = object (original);
  Clone.sayhi = function () {
    alert (' Hi ');
  }
  return clone;
}

Use examples:

/* Prototype inheritance */
function object (o) {
  function F () {}
  f.prototype = O;
  return new F ();
}
   
/* Parasitic inheritance *
/function Createanother (original) {
  var clone = object (original);
  Clone.sayhi = function () {
    alert (' Hi ');
  }
  return clone;
}

var person = {
  name: ' Wuyuchang ',
  friends: [' wyc ', ' Nicholas ', ' Rose ']
}
var Anotherperson = Createa nother (person);
Anotherperson.sayhi ();

Parasitic Modular Inheritance

Previously said the Javascrip in the combination of the inheritance of the shortcomings, now we have to solve its shortcomings, the implementation of the idea is, for the constructor inherited properties, and the prototype chain of the hybrid form of inheritance method, that is, do not inherit the method when the constructor of the parent type. The code is as follows:

function Object (o) {
  function F () {}
  f.prototype = O;
  return new F ();
}

/* Parasitic Modular inheritance *
/function Inheritprototype (subtype, supertype) {
  var prototype = object (Supertype.prototype); C29/>prototype.constructor = subtype;
  Subtype.prototype = prototype;
}

When used, only the "Subtype.prototype = new Supertype ()" In the combined mode is required; This line of code is replaced with Inheritprototype (subtype, supertype); High efficiency of parasitic modular inheritance it only calls one parent type constructor at a time, avoiding the creation of unnecessary or superfluous attributes. At the same time, the prototype chain can remain unchanged, so that instanceof and isprototypeof () can be used normally. This is also the most ideal way to inherit the present, and is now in transition to this model. (Yui also used this mode.) )

This blog post refers to the JavaScript Advanced Programming 3rd edition, the code is rewritten, more specific, and annotated to make it easier to understand. such as the JS inheritance has a unique view of children's shoes do not stingy, reply to your views for your reference!

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.