JavaScript Inherits Learning Notes

Source: Internet
Author: User

JavaScript as an object-oriented language (JS is an object-based), can implement inheritance is necessary, but because it does not have the concept of class, so it does not like the real object-oriented programming language through the class implementation of inheritance, but can be implemented by other methods to implement inheritance. (in JavaScript, inheritance is http://www.cnblogs.com/amumustyle/p/5435653.html through the prototype chain) There are many ways to implement inheritance, and here are just a few of them.

I. Prototype chain inheritance

1         function Person () {//inherited functions are called supertype (parent class, base class)2 this.name= ' Mumu ';3 this.age= ' + ';4         }5         6 person.prototype.name= ' susu ';////When the attribute name is the nearest principle, look it up in the instance and find it in the prototype .7               8 function Worker () {//inherited functions are called subtypes (subclasses, derived classes)9 this.job= ' student ';Ten         } One  A worker.prototype=new person ();//through the prototype chain inheritance, the superclass instantiation of the object instance, assigned to the child class prototype properties - var p2=new Worker (); -  the Console.log (p2.name); -Console.log (P2 instanceof object);//ture all constructors inherit from object

The key to realize the above inheritance is: worker.prototype=new person (); The prototype of the worker becomes an instance of the person, inherited through the prototype chain.

Note: When implementing inheritance using a prototype chain, you cannot use object literals to create a prototype method, because it breaks the relationship and overrides the prototype chain.

Prototype chain inheritance issues:

1. There is a reference sharing problem, they still share a space, the subclass affects the parent class

1         function Person () {2 this.bodys=[' eye ', ' foot '];3         }4         5 function Worker () {6         }7 8 worker.prototype=new person ();9 var p1=new Worker ();Ten P1.bodys.push (' hand '); One var p2=new Worker (); A Console.log (P1.bodys); -Console.log (P2.bodys);

2. When you create an instance of a subtype, you cannot pass parameters as a constructor of a superclass.

So how to solve the two problems of the prototype chain? Then continue to see the following way of inheritance ~

Two. Borrowing constructor inheritance (also called object impersonation, forgery object, or classic inheritance)

1 function Person (name,age) {2 This.name=name;3 This.age=age;4 this.bodys=[' eye ', ' foot '];5     }6 7 person.prototype.showname=function () {8 Console.log (this.name);9     }Ten  One function Worker (name,age,job) { A Person.call (this,name,age); - this.job=job;//Adding a property to a sub-class -     } the  - var p1=new Worker (' Mumu ', ' 18 ', ' Student '); - P1.bodys.push (' hand '); - var p2=new Worker (); +  - Console.log (p1.name); + Console.log (P2.bodys); AConsole.log (P1.showname ());

Simple analysis of the use of the above-borrowed constructor principle:Person.call (this,name,age); This code calls the parent constructor , inherits the Parent property, calls the person constructor with the call method, changes the this when the function executes, this-> New a worker Object Constructor Camouflage method: The worker is passed to the person above .

When the reference type is placed inside the constructor, it is not shared, so the P2 is not affected.

The use of the constructor inheritance method solves the problem that the prototype chain cannot pass parameters and the reference type is shared.

Tip: The call() and apply () methods can change the scope of function execution , in short, change the function in this point to the content.

Both call () and apply () accept two parameters: the first is the scope in which the function is run, and the other is the passed parameter.

The difference between call and apply is that the parameters are different .
The parameters in call must be enumerated one after the other .
the argument in apply must be an array or a arguments object

So the question is: Why is the p1.showname () result wrong? ---- because borrowing constructor inheritance only inherits properties and methods in the constructor. A problem with borrowing a constructor is also found here.

Note: because the method is put in the constructor, each time we instantiate will allocate memory space for it to cause the waste of resources, so we usually put the method in the prototype, the attribute is placed in the constructor.

To borrow a constructor inheritance problem:

Because the borrowing constructor can only inherit properties and methods from constructors, the methods defined in the prototype of the superclass are not visible to the subclass, so it is equivalent to not having a prototype. As a result, all methods can only be defined in the constructor, so there is no function reuse.

So how do you solve the problem of borrowing a constructor function? That depends on the way we inherit.

Three. Combination inheritance (pseudo classic inheritance)

1 function Person (name,age) {2 This.name=name;3 This.age=age;4     }5 6 person.prototype.showname=function () {7 Console.log (this.name);8     }9 Ten function Worker (name,age,job) { One Person.call (this,name,age);//borrowing constructors A This.job=job; -     } -      the worker.prototype=new person ();//prototype chain inheritance - var p1=new Worker (' Mumu ', ' 18 ', ' Student '); -  - Console.log (p1.age); +P1.showname ();

Combinatorial inheritance: Combines a prototype chain with a borrowed constructor.

Idea: Using the prototype chain to implement the property and method inheritance on the prototype, borrowing the constructor to implement the inheritance of the instance property

The above example Person.call (This,name,age); the borrowing constructor inherits the property

Worker.prototype=new person (); The prototype chain inherits the method, avoids the disadvantage of the two, blends their advantages and becomes the most common inheritance pattern.

Problem with combinatorial inheritance:

A two-time super-type constructor is called, one time when a subtype prototype is created, and the other is inside the constructor of the sub-type.

To solve this problem, we need to use the parasitic combined inheritance mode.

Four. prototype-Type Inheritance

1 function Object (proto) {2 function F () {}3 f.prototype = Proto;4 return new F ();5     }6 7 var person = {8 name: ' Mumu ',9 friends: [' xiaxia ', ' susu ']Ten     }; One  A var Anotherperson = object (person); - anotherPerson.friends.push (' Wen '); - var Yetanotherperson = object (person); the anotherPerson.friends.push (' Tian '); - Console.log (person.friends);//["Xiaxia", "Susu", "Wen", "Tian"] -Console.log (anotherperson.__proto__)//object {name: "Mumu", Friends:array[4]}

Simple analysis: Functionobject (proto) is a temporary transfer function, the parameters inside the Proto represents an object that will be passed in,F () constructor is a temporary new object used to store objects passed in. f.prototype = Proto; assigns an object instance to a value of F The prototype object of the constructor, and finally returns an object instance of the object passed. The properties of the reference type are also shared by the stereotype inheritance.

Five. Parasitic inheritance

1 //Temporary transfer function2 function Object (proto) {3 function F () {}4 f.prototype = Proto;5 return new F ();6     }7 8 //Parasitic functions9 function Create (proto) {Ten var f=object (proto); One f.love=function () { A return this.name; -         } - return F; the     } -  - var person = { - name: ' Mumu ', + friends: [' xiaxia ', ' susu '] -     }; +  A var Anotherperson = create (person); atConsole.log (Anotherperson.love ()); parasitic combined inheritance

Six. Parasitic combined inheritance

1 function Object (proto) {2 function F () {}3 f.prototype = Proto;4 return new F ();5     }6 7 //Parasitic functions8 function Create (person,worker) {9 var f=object (person.prototype);//Create ObjectTen f.constructor=worker;//Adjust the prototype construction pointer to enhance the object One worker.prototype=f;//the specified object A     } -      - function Person (name,age) { the This.name=name; - This.age=age; -     } - person.prototype.showname=function () { + Console.log (this.name); -     } + function Worker (name,age,job) { A Person.call (this,name,age); at This.job=job; -     } -      - Create (Person,worker);//parasitic combined inheritance - var p1=new person (' Mumu ', ' 18 ', ' Student '); -P1.showname ();

This method is also the most perfect and ideal to implement the inheritance method now.

JavaScript Inherits Learning Notes

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.