Introduction to several inheritance methods of javascript _ basic knowledge

Source: Internet
Author: User
The following section introduces several inheritance methods of javascript. I think it is quite good. Now I will share it with you for your reference. 1. prototype chain inheritance:Constructor, prototype, and instance relationships: Each constructor has a prototype object that contains a pointer to the constructor, the instance contains an internal pointer to the prototype object. Instanceof is used to confirm the relationship between the prototype and the instance.

Disadvantages of prototype chain inheritance: literal rewriting of prototype will interrupt the relationship, use the prototype of the reference type, and the child type cannot pass parameters to the super type

Function Parent () {this. name = 'Mike ';} function Child () {this. age = 12;} // son inherits father (prototype chain) Child. prototype = new Parent (); // Child inherits the Parent and uses the prototype to form the chain var test = new Child (); console. log (test. age); console. log (test. name); // get the inherited attributes // The grandson continues the prototype chain to inherit the son function Brother () {this. weight = 60;} Brother. prototype = new Child (); // inherit the prototype chain to inherit var brother = new Brother (); console. log (brother. name); // inherits Parent and Child. the pop-up mike console is displayed. 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 forged objects or classic inheritance.
Constructor implementation inheritance disadvantages: although the borrow constructor solves the two problems of prototype chain inheritance, but there is no prototype, it cannot be reused. Therefore, the prototype chain + borrow constructor mode is required.

Function Parent (age) {this. name = ['Mike ', 'jack', 'Smith']; this. age = age;} function Child (age) {Parent. call (this, age); // point this to the Parent, and you can also pass the parameter} var test = new Child (21); console. log (test. age); // 21 console. log (test. name); test. name. push ('bill '); console. log (test. name); // mike, jack, smith, bill

3. Combined inheritance:The prototype chain is used to inherit the prototype attributes and methods, and the constructor is used to inherit the instance attributes. In this way, function reuse is realized by defining methods in the prototype, and each implementation has its own attributes.

Disadvantage: in any situation, two super-Type constructor will be called. One is when the sub-type prototype is created, and the other is when the sub-type prototype is created, the other is in the Child Type 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); // transmits parameters to the super-type, second call} Child. prototype = new Parent (); // prototype chain inheritance. The first call var test1 = new Child (21); // write new Parent (21) to the console. log (test1.run (); // mike, jack, smith are both 21 var test2 = new Child (22); console. log (test2.age); console. log (test1.age); console. log (test2.run (); // This allows test1 and test2 to have their own property age and run methods.

4. Original Type inheritance:The prototype allows you to create new objects based on existing objects without creating custom types. It requires that one object can be used as the basis of 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 standardizes the original type inheritance by adding the Object. create () method. This method receives two parameters: an Object used as the new Object prototype and (optional) an Object that defines attributes 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", "j Im "," lucy "," Rob "," Barbie "]/* Any attribute specified in this way will overwrite the Same Name attribute on the prototype object. */Var threeP = Object. create (person, {name: {value: 'red'}); console. log (threeP. name); // red. If no name exists in threeP, The nicho value in person2 is output.

5. Parasitic inheritance:The idea is similar to the parasitic constructor and the factory mode, that is, to create a function that is only used to encapsulate the inheritance process. This function internally enhances the object in some way, finally, it returns the object just as it does all the work.

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 person. The new object not only has all attributes and methods of person, but also has its own sayHi () method */

Parasitic combined inheritance: in any situation, two super-Type constructor is called. One is when the sub-type prototype is created, and the other is when the sub-type prototype is created, the other is within the child Type constructor, so that the type will eventually contain all the instance attributes of the super type object. We have to rewrite these attributes when calling the child Type constructor. Therefore, parasitic combined Inheritance occurs.

6. Parasitic combined inheritance:The constructor is used to inherit attributes, and the methods are inherited through the mixed form of the prototype chain. Basic Idea: you do not have to call a super-Type constructor to specify the sub-type prototype. Essentially, the super-type prototype is inherited using parasitic inheritance, and then the result is specified to the sub-type prototype.

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 of this function is to create a copy of the super-type prototype. The second step is to add the constructor attribute to the created copy, * to compensate for the default constructor attribute lost due to the prototype rewriting. The third step is to add the new object (copy) the prototype assigned to the child type */function inheritPrototype (subType, superType) {var prototype = object (superType. prototype); // create the prototype object. constructor = subType; // enhancement object subType. prototype = prototype; // specify the 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)

Advantages of this method: Only one SuperType constructor of the parent class is called, and unnecessary attributes are not created on SubType. prototype. At the same time, the prototype chain can remain unchanged, and instanceof and isPrototypeOf () can be used normally ();

The introduction of several inheritance methods in this javascript article is all the content that I have shared with you. I hope you can give me a reference and support me a lot.

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.