Javascript-prototype, inheritance-02

Source: Internet
Author: User

Prototype chain

First, the relationship between the real column, the constructor and the prototype object is reviewed.

The real column contains a pointer to the prototype object (_PROTO_);

Constructors have prototype (prototype attributes) pointers to prototype objects;

A prototype is an object that also has an internal property (_proto_) that points to the parent class (the previous level) of the prototype object;

Then the prototype chain is: the example through the _proto_ recursive to find the example and prototype chain (except object, it is the base class);

function Person () {    }

Chain diagram:

Summarize:

1. All reference types inherit object by default

2. The default prototype for all functions is an instance of object, similar to the following: The prototype object is =new objects (), so the default prototype will contain an internal pointer (_proto_), pointing to Object.prototype;

3. All reference type objects have a _proto_ attribute pointing to the prototype object, all function objects have prototype properties, pointing to the prototype object;

Prototype chain-Inheritance

There are two ways I know of inheritance:

1, interface inheritance: only inherit the method signature;

2, the realization of inheritance: The method of inheriting the actual;

Because the function in JS is not signed, it cannot implement interface inheritance, only supports method inheritance, and it is implemented by the prototype chain.

 function   person (name, age, sex) {this . Name = name;           sex; } Person.prototype.sayHello  =function  () {console.log ("Hello word!"    function   Man () {} Man.prototype  = new      person ();  var  instance=new   man (); Console.log (Instance.sayhello);//Hello word!  

The above is a simple inheritance, the man prototype pointer to an instance of person, so that the new man () instance can access to the SayHello method in person;

The prototype chain also has some problems to change the above code:

    functionPerson (name, age, sex) { This. Name =name;  This. Age =Age ;  This. Sex =sex;  This. color=["Red", "Blue", "green"]; } Person.prototype.sayHello=function() {console.log ("Hello word!")}; functionMan () {} Man.prototype=NewPerson (); varInstance=NewMan (); Instance.color.push ("Black"); Console.log (Instance.color);//["Red", "Blue", "green", "black"]    varInstance2=NewMan (); Console.log (Instance2.color); //["Red", "Blue", "green", "black"]

We know that prototypes are shared properties and methods for all instances, and when prototypes are used to implement inheritance, the prototypes actually become instances of another type, so the problem arises.

Combining inheritance

The principle of combinatorial inheritance is simple, when constructing a subclass object instance by changing the this pointer so that the subclass object instance has the parent class property and its own constructed property, so that there is a separate copy of the property between the instances.

The inheritance of the method is still implemented by the prototype, see the code:

  functionPerson (name, age, sex) { This. Name =name;  This. Age =Age ;  This. Sex =sex;  This. color=["Red", "Blue", "green"]; } Person.prototype.sayHello=function() {console.log ("Hello word!")}; functionMan (name,age,sex,job) {Person.call ( This, Name,age,sex);  This. job=job; } Man.prototype=NewPerson (); varInstance=NewMan ("Zhang San", 20, "male", "Farmer"); Instance.color.push ("Black"); Console.log (Instance.color);//["Red", "Blue", "green", "black"]Console.log (Instance.job);//FarmersConsole.log (Instance.sayhello);//Hello word!    varInstance2=NewMan ("Zhang San", 20, "male", "landlord"); Console.log (Instance2.color); //["Red", "Blue", "green"]Console.log (Instance2.job);//landlordConsole.log (Instance2.sayhello);//Hello word!

By pointing to the parent class in the constructor, so that the instance object has a property of the parent class, the previous theory is that the search principle starts with the instance, and even if the prototype object is an instance object of the parent class, the attribute is taken from the instance object;

The combination mode is the common way of inheritance in JavaScript;

Call, apply, bind (BIND)

In JavaScript, functions can change their this point in 3 ways, which are call, apply, bind. 3 of them are very similar, but there are differences. The table below can be very intuitive to see the difference between the three

method whether to execute functions directly incoming parameters call Way
call

(context,arg1,arg2,arg3 ...)

The second argument is followed by an argument

Function.call (Context,arg1,arg2,arg3 ...)

apply Yes

(context,[ar G1,arg2,arg3 ...])

The second argument must be an array

Function.apply (Context,[arg1,arg2,arg3 ...])

bind no

(context,arg1,arg2,arg3 ...)

The second argument is followed by an argument

var newfunction = function.bind (context);

Newfunction (Arg1,arg2,arg3 ...)

 

Call and apply features: invokes the current function with the specified object. Call and apply function exactly the same, just slightly different in syntax.

Call:
var a = {x:1};     var function (Y, z) {        console.log (this. x + y + z)    };      3, 4); // the This of B (that is, the context at which B executes) is changed to a, so this.x is 1 and the second argument is passed to the B argument. 
Apply
var a = {x:1};     var function (arr) {        Console.log (this. x + arr[0] +arr[1])    };    B.call (A, [3, 4]); // this at this point (that is, the context of B execution) is changed to a, the second argument is an array
Bind
var a = {x:1};     var function (Y, z) {        console.log (this. x + y + z)    };      var newb = B.bind (a); // the This of B (the context at which B executes) is changed to a so that a new function is generated, and the function is not executed immediately.     newb (3, 4);   function does not execute at this time

Call or apply is executed immediately after the execution context object has been swapped, and bind is a new function that is created after swapping the execution context object.

functionFun () {Console.log ( This. Name); }           functionobj1 () { This. Name = ' call| | Apply; }           functionObj2 () { This. Name = ' bind '; }           varO1 =Newobj1 (); varO2 =NewObj2 ();           Fun.call (O1); //to manually invoke the new function created by bindFun.bind (O2) ();

On the internet to find a more complete prototype chain diagram:

Summarize

1, the formation of the prototype chain is really by _proto_, pointing to the prototype object;

2, the reference type is inherited by default object;

3, the default prototype of all functions is an object instance, that is, the default prototype object also has an internal property _proto_ point to Object prototype;

4, Function.prototype is the prototype of the function type;

5, the inheritance is mainly based on the prototype chain implementation, and the prototype chain is mainly based on the example and prototype object chain implementation, reference type any object has internal properties _proto_ point to the prototype object;

Javascript-prototype, inheritance-02

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.