Several methods of inheriting JavaScript introduction _ Basic Knowledge

Source: Internet
Author: User
Tags inheritance

1. Prototype chain inheritance: The relationship between constructors, prototypes, and instances: each constructor has a prototype object that contains a pointer to the constructor, and the instance contains an internal pointer to the prototype object. Confirm the relationship between the prototype and the instance with instanceof.

Prototype chain inheritance disadvantage: Literal rewrite prototypes break relationships, use prototypes of reference types, and subtypes cannot pass arguments to super types

function Parent () {
    this.name= ' Mike ';
  }
  function Child () {
    this.age=12;
  }
  The son inherits the father (prototype chain)
  child.prototype=new parent (),//child inherits the parent, and forms the chain
  var test=new child () through the prototype;
  Console.log (test.age);
  Console.log (test.name);//Get inherited attribute
  //grandson continue prototype chain inherit son
  function Brother () {
    this.weight=60;
  }
  Brother.prototype=new Child ();//inheriting prototype chain inherits
  var brother=new Brother ();
  Console.log (Brother.name)//Inherits parent and child, pops up Mike
  Console.log (brother.age)//12 Console.log

  (brother instanceof child);//ture
  Console.log (brother instanceof Parent);//ture Console.log
  (brother instanceof Object);//ture

2. Constructor implementation inheritance: also known as false object or classic inheritance.
Inheritance disadvantage of constructors: Although the use of constructors solves two problems of prototype chain inheritance, there is no prototype, so reuse is impossible to talk about, so we need prototype chain + borrowing constructor mode.

function Parent (age) {
    this.name=[' Mike ', ' Jack ', ' Smith '];
    this.age=age;
  }
  function Child (age) {
    parent.call (this,age);//point this to Parent, while also passing parameters
  }
  var test=new child.
  Console.log (test.age);//21
  Console.log (test.name)

  ; Test.name.push (' bill ');
  Console.log (test.name);//mike,jack,smith,bill

3. Combinatorial inheritance: using prototype chains to implement inheritance of prototype properties and methods, and by borrowing constructors to implement inheritance of instance properties. This means that the function is reused by defining the method on the prototype, and that each implementation has its own attribute.

Disadvantage: In any case, the two-time superclass constructor is invoked, one time when the subtype prototype is created, the other is when the subtype prototype is created, and the other is inside the subtype constructor.

function Parent (age) {
    this.name=[' Mike ', ' Jack ', ' Smith '];
    this.age=age;
  }
  Parent.prototype.run=function () {return
    this.name+ ' are both ' +this.age;
  }
  function Child (age) {
    parent.call (this,age);//Give super type parameters, second call
  }
  child.prototype=new Parent ();//prototype chain inheritance, The first call to
  var test1=new child (21);//write New Parent (21) also line
  Console.log (Test1.run ());//mike,jack,smith are both 21

  var test2=new child ();
  Console.log (test2.age);
  Console.log (test1.age);
  Console.log (Test2.run ());
  This allows test1 and test2 to have their own attribute age, while also having the Run method

4. Prototype inheritance: by using prototypes, you can create new objects based on existing objects without having to create custom types. It requires that an object be able to be the basis for another object.

function Object (o) {
    function F () {};
    f.prototype=o;
    return new F ();
  }
  var person={
    name: ' Nicho ',
    friends:[' shell ', ' Jim ', ' Lucy ']
  }
  var Anotherperson = object (person);
  Anotherperson.name = ' Greg ';
  AnotherPerson.friends.push (' Rob ');
  Console.log (anotherperson.friends),//["Shell", "Jim", "Lucy", "Rob"]

  var Yetanotherperson = object (person);
  Yetanotherperson.name = ' Linda ';
  YetAnotherPerson.friends.push (' Barbie ');
  Console.log (yetanotherperson.friends)//["Shell", "Jim", "Lucy", "Rob", "Barbie"]

  console.log (person.friends) //["Shell", "Jim", "Lucy", "Rob", "Barbie"

ECMAScript5 normalized the stereotype inheritance with the new Object.create () method, which receives two parameters: an object that serves as a prototype for the new object and (optionally) an object that defines the property for the new object.

var person2={
    name: ' Nicho ',
    friends:[' shell ', ' Jim ', ' Lucy ']
  };
  var anop2=object.create (person2);
  Anop2.name= "Greg";
  AnoP2.friends.push (' Rob ');
  Console.log (anop2.friends),//["Shell", "Jim", "Lucy", "Rob"]

  var yetp2=object.create (person2);
  Yetp2.name= "Linda";
  YetP2.friends.push (' Barbie ');
  Console.log (yetp2.friends);//["Shell", "Jim", "Lucy", "Rob", "Barbie"]

  console.log (person2.friends);//["Shell "," Jim "," Lucy "," Rob "," Barbie "]/
  * Any property specified in this manner overrides an attribute of the same name on the prototype object. * *
  var threep=object.create (person,{
    name:{value: ' Red '}
  });
  Console.log (threep.name);//red, if no name is in Threep, output Person2 Name value Nicho

5. Parasitic inheritance: thinking like a parasitic constructor and factory pattern, you create a function that encapsulates only the inheritance process, which in some way enhances the object, and finally, as it does all the work, returns the object.

function Object (o) {
    function F () {};
    f.prototype=o;
    return new F ();
  };
  function Createanother (o) {
    var cl=object (o);
    Cl.sayhi=function () {
      console.log (' Hi ');
    }
    return cl;
  };
  var person={
    name: ' Nick ',
    friends:[' Shelby ', ' Court ', ' Van '
  }
  var anotherperson=createanother (person);
  Anotherperson.sayhi ();//hi
  Console.log (anotherperson.name);//nick
  Console.log (anotherperson.friends) //["Shelby", "court", "Van"]/

  * The code in this example returns a new object--anotherperson based on the person. The new object not only has
   all the attributes and methods of person, but also has its own sayhi () method.

Parasitic modular inheritance: In any case, the two-time super type constructor is invoked, one time when the subtype prototype is created, the other is when the subtype is created, and the other is inside the subtype constructor, which eventually contains all the instance properties of the superclass object. We have to override these properties when calling the subtype constructor. Therefore arose the parasitic modular inheritance.

6. Parasitic Modular Inheritance: Use the constructor to inherit the property, and inherit the method through the hybrid form of the prototype chain. Basic idea: You do not have to call a superclass constructor in order to specify a stereotype of a subtype. The essence is to use parasitic inheritance to inherit the superclass of the super type, and then assign the result to the subtype of the stereotype.

 function supertype (name) {this.name=name;
  this.colors=[' red ', ' blue ', ' green ';
  } supertype.prototype.sayname=function () {console.log (this.name);
    Function subtype (name,age) {supertype.call (this,name);
  This.age=age;
    function Object (o) {function F () {};
    F.prototype=o;
  return new F ();
  }; /*inheritprototype The first step in this function is to create a copy of the Super type prototype. The second step is to add the constructor attribute for the created copy, * To compensate for the default constructor property lost by overriding the prototype, and the third to assign the newly created object (copy) to the subtype of the prototype/function Inheritprototype ( Subtype,supertype) {var prototype=object (supertype.prototype);//Create Object prototype.constructor=subtype;//Enhanced Object SubT
  ype.prototype=prototype;//the specified object} inheritprototype (Subtype,supertype);
  Subtype.prototype.sayage=function () {console.log (this.age);
  } var p=new subtype (' Xiaoli ', 24);
  Console.log (P.sayname ());
  Console.log (P.sayage ()); Console.log (p.colors) 

The advantage of this method is that only one parent class Supertype constructor is called, and thus avoids creating unnecessary unwanted properties on subtype.prototype. At the same time the prototype chain can remain unchanged, but also the normal use of instanceof and isprototypeof ();

Above this javascript several kinds of inheritance method introduction is small series to share to everybody's content, hoped can give everybody a reference, also hoped that everybody supports the cloud habitat community.

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.