JS prototype chain

Source: Internet
Author: User

1.1 Understanding the prototype chain

Almost everything in JavaScript is an object, and we say that arrays are objects, DOM nodes are objects, functions, and so on are objects, and objects that create objects, which are themselves constructors, have an important problem:对象从哪里来?

This is a nonsense, the object of course is created through a certain way, depending on the actual type, the way objects are created varies widely. such as functions, we can declare functions, use function constructor creation, such as arrays, we can directly through the var arr = [] To create an empty array, or can be created through the new array, such as ordinary objects, we can literally create, Create with built-in constructors and so on, so many tricks, so much so that when we learn the dizzy brain rise, no avail.

In fact, all "type" objects can be thought of as being created by the corresponding constructor. Functions are instantiated by a function constructor, an ordinary object is instantiated by an object constructor, and an array object is instantiated by an array constructor, as for object | Array | function and so on they are functions themselves, of course, they also have their own constructors.

Understanding the above point, then we will be much easier to understand the prototype chain.

Take a look at the stimulus derivation process

As a precondition, all objects are instantiated by constructors, and constructors have a prototype object associated with them by default.
? The prototype object of the ① constructor is also an object and therefore has its own constructor
? ② constructor of a constructor prototype object, and also a prototype object associated with it
? The prototype object () of the ③ constructor prototype object ( __proto__ ) also has its own constructor, which also has an associated prototype object
? The above form a chain-like access structure, is for 原型链 .

The constructor is also an object, so the constructor itself has its own constructor as an object, and this constructor has a prototype object associated with it, and so on. So, this is another prototype chain. In conclusion, we can draw 原型链并不孤单The conclusion.

1.2 Prototype chain structure

Now that we have basically made the origin of the prototype chain clear, then we will analyze the overall structure of the prototype chain through specific code.

Sample code

1  //01 Custom Constructors person and Animal2 function person () {}3 function Animal () {}4//02 use constructors to create instance objects 5 var p1 = new Person (); 6 VA R P2 = new Person (); 7 var a = new Animal (); 8  //03 Create array object 9 var arrm = ["Demoa", "demob"];

The above code is very simple, where p1,p2 and a are instantiated objects of custom constructors. Second, we created the ARRM array with a shortcut, and ARRM is actually an instantiated object of the built-in constructor array. In addition, both the person and animal are actually instance objects of the function constructor. After understanding the above, we can take a look at the prototype chain diagram for these lines of code.

Prototype chain structure diagram Description:

① because of the complexity relationship, the prototype chain structure diagram of the Arrm object is given separately. The ②object.prototype is the top of all the prototype chains and the end point is null.

Verifying the code associated with the prototype chain

 1//[1] Verify that the prototype object for P1, p2 is person.prototype 2//Verify a prototype object is Animal.prototype 3 console.log (p1.__proto__ = = Person.prototy PE); True 4 Console.log (p2.__proto__ = = Person.prototype);  True 5 Console.log (a.__proto__ = = Animal.prototype); True 6//[2] Get person.prototype| Animal.prototype Constructor 7//Verify person.prototype| Animal.prototype prototype object for Object.prototype 8//Delete instance member first, Access 9 delete person.prototype.constructor;10 Delete Animal.pr by prototype member    Ototype.constructor;11 Console.log (Person.prototype.constructor = = Object);    True12 Console.log (Animal.prototype.constructor = = Object);    True13 Console.log (person.prototype.__proto__ = = Object.prototype);    True14 Console.log (animal.prototype.__proto__ = = Object.prototype); TRUE15//[3] Verify that the constructor for person and animal is an empty function for Function16//validating the person and animal constructors for the prototype object (Console.log = =                Function);                True18 Console.log (Animal.constructor = = Function); True19 Console.log (person.__proto__ = = Function.protOtype);        True20 Console.log (animal.__proto__ = = Function.prototype);    TRUE21//[4] Verify that the Function.prototype constructor is Function22 console.log (Function.prototype.constructor = = function);              True23//[5] verifies that the constructor for function and object is Function24 console.log (function.constructor = = function);                True25 Console.log (Object.constructor = = Function); True26//[6] Verify that the Function.prototype prototype object is Object.prototype instead of its own console.log (function.prototype.__proto__ = =                    Object.prototype);//true28//[7] Get the end point of the prototype chain Console.log (OBJECT.PROTOTYPE.__PROTO__); Null

The following is a prototype chain diagram with a set of objects attached

code example for validating array object prototype chain structure

1//[1] Verify that the Arrm constructor is array 2//Method 1 3 console.log (arrm.constructor = = array);                 True 4//Method 2 5 Console.log (Object.prototype.toString.call (ARRM));      [Object array] 6//[2] verifies that the constructor of the Array is function 7 console.log (Array.constructor = = function);             True 8//[3] Verify that the prototype object of the Array constructor is Function.prototype (null function) 9 Console.log (array.__proto__ = = Function.prototype);     True10//[4] Verify that the Array.prototype constructor is object and the prototype object is OBJECT.PROTOTYPE11 delete array.prototype.constructor;12 Console.log (Array.prototype.constructor = = Object);         True13 Console.log (array.prototype.__proto__ = = Object.prototype); True
1.3 Access to the prototype chain

Access rules for the prototype chain

Object when accessing the property or method, first check its own instance member, if it exists then directly use, if not exist then find the object's prototype object, find the prototype object above whether there is a corresponding member, if there is so direct use, if not then follow the prototype chain upward search, if found to use, If it is not found, repeat the process until the top of the prototype chain, if the access is a property to return undefined, the method error.

1 function person () {2     this.name = "wendingding"; 3} 4 Person.prototype = {5     Constructor:person, 6     name: "Unsolicited Cooked ", 7     showname:function () {8         this.name.lastIndexOf () 9     }10};11 var p = new person (); Console.log (p.name);   //access is the name attribute above the instance member: Wendingding13 p.showname ();          Print Wendingding14 console.log (p.age);    The property does not exist in the prototype chain and returns UNDEFINED15 P.showage ();           This property does not exist in the prototype chain, error

Description of concepts and access principles
? Instance member: A property or method of an instance object
? Prototype Member: A property or method of the prototype object of an instance object
? Access principle: The nearest principle

1.4 getprototypeof, isprototypeof and instanceof

The object.getprototypeof method is used to get the prototype object of the specified instance object, and the usage is very simple, simply passing the instance object as a parameter, and the method returns the prototype object of the current instance object to us. To be blunt, this static method of object is the function of returning the prototype prototype that the instance object __proto__ attribute points to.

1  //01 Declaration constructor F2 function f () {}3//02 use constructor f to get instance object f4 var f = new F (); 5//03 test getprototypeof method Use 6 Console.log (Object . getprototypeof (f));  The result of printing is an object that is an F-associated prototype object 7 Console.log (object.getprototypeof (f) = = = F.prototype);  True8 Console.log (object.getprototypeof (f) = = = f.__proto__);  True

The isprototypeof method is used to check whether an object is in the prototype chain of the specified object, and if so, returns true if the result is false otherwise.

1//01 Declaration Constructor Person 2 function person () {} 3//02 get instantiated object P 4 var p = new person (); 5//03 Test isprototypeof use 6 console.log (Person.prototype.isPrototypeOf (p)); True 7 Console.log (Object.prototype.isPrototypeOf (p)); True 8 var arr = [n/a]; 9 Console.log (Array.prototype.isPrototypeOf (arr));    True10 Console.log (Object.prototype.isPrototypeOf (arr));   True11 Console.log (Object.prototype.isPrototypeOf (person));//true

The prototype chain of the above code
①p–>person.prototype–>object.prototype–>null
②arr–>array.prototype–>object.prototype–>null
Object.prototype is at the top of all prototype chains, so all instance objects inherit from Object.prototype

The instanceof operator is similar to the isPrototypeOf method, the left operand is the instance object to be detected, and the right operand is the constructor used for detection. If the right operand specifies that the prototype object of the constructor is above the prototype chain of the left operand instance object, the result is true, otherwise the result is false.

1  //01 Declaration Constructor Person 2 function person () {} 3//02 get instantiated object P 4 var p = new Person () 5//03 test isprototypeof use 6 console . log (P instanceof person);   True 7 Console.log (P instanceof Object);   True 8 The prototype object of the//04 objects constructor is in the prototype chain of function This instance object 9 Console.log (function instanceof object); The prototype object of the True10//05 function constructor is console.log (object instanceof function) in the prototype chain of the object instance True
Note: Do not mistakenly think that the instanceof check is 该实例对象是否从当前构造函数实例化创建的, it checks whether the instance object inherits properties from the prototype object of the currently specified constructor.

We can further understand the code examples given below

1  //01 Declaration Constructor Person 2 function person () {} 3//02 get instantiated object P 4 var p1 = new Person () 5//03 test isprototypeof use 6 consol E.log (P1 instanceof person);   True 7//04 replaces the person's default prototype object 8 Person.prototype = {9     constructor:person,10     showinfo:function () {         One Console.log ("xxx");     }13};14//05 Reset the constructor prototype object, since Person15 Console.log (P1 instanceof person); False16//06 re-creates the instantiated object after the person constructor resets the prototype object, var p2 = new Person (), Console.log (P2 instanceof person);   TRUE19//==> recommended that in development, the prototype object of the constructor is always set before the instantiation object is created

Prototype chain diagram (partial) with the above code posted

1.5 Inheritance related to the prototype chain

Inheritance is one of the basic features of object-oriented programming, JavaScript supports object-oriented programming, and there are a number of possible scenarios for implementing inheritance. Next, let's get to know each other 原型式继承、原型链继承以及在此基础上演变出来的组合继承 .

Basic style of prototype inheritance

1  //01 provides supertype | Parent type Constructor 2 function superclass () {} 3//02 set the prototype property and prototype method of the parent type 4 SuperClass.prototype.info = ' superclass information ';  5 SuperClass.prototype.showInfo = function () {6     console.log (This.info); 7}; 8//03 provides subtype 9 function subclass () {}10 04 Set Inheritance (Prototype object inheritance) One Subclass.prototype = superclass.prototype;12 SubClass.prototype.constructor = subclass;13 var sub = n EW subclass (); Console.log (sub.info);          Superclass information of Sub.showinfo ();                 Superclass's information

Post-prototype inheritance structure diagram

Tip This way you can inherit a prototype member from a superclass, but there is a problem sharing with the Superclass prototype object

Prototype chain inheritance

Realize the idea

Core: Sets the instance object of the parent class to the prototype object of the subclass Subclass.prototype = new Superclass ();
Problem: Unable to pass parameters for parent constructor (superclass)

Prototype chain inheritance basic notation

1//01 offers super type | Parent Type 2 function superclass () {3     this.name = ' superclass name '; 4     this.showname = function () {5         Co Nsole.log (this.name); 6     } 7} 8//02 set the prototype properties and prototype method of the parent type 9 SuperClass.prototype.info = ' superclass information '; SuperClass.prototype.showInfo = Functi On () {     console.log (this.info); 12};13//03 provides subtypes of function subclass () {}15//04 Set Inheritance (prototype object inheritance)-var sup = new Super Class (); subclass.prototype = sup;18 SubClass.prototype.constructor = subclass;19 var sub = new subclass (); Console.lo g (sub.name);          Superclass's name is Console.log (sub.info);          Superclass's information is Sub.showinfo ();                 Superclass information at Sub.showname ();                 Name of the superclass

Post the prototype chain inheritance structure diagram

Combining inheritance

Realize the idea

① using prototype chains for inheritance of prototype properties and methods
② inherits the instance members by forging (impersonating) a constructor, and resolves the parent constructor argument

Composition Inheritance Basic notation

1  //01 offers super type | Parent Type 2 function superclass (name) {3     this.name = name; 4     this.showname = function () {5         Conso Le.log (this.name); 6     } 7} 8//02 set the prototype properties and prototype method of the parent type 9 SuperClass.prototype.info = ' superclass information '; SuperClass.prototype.showInfo = Functi On () {     console.log (this.info); 12};13//03 provides subtypes of function subclass (name) {     superclass.call (this,name); 16}17//(1) Gets the instance member of the parent constructor  Person.call (this,name); 18//(2) Gets the prototype member of the parent constructor  Subclass.prototype = superclass.prototype;19 Subclass.prototype = superclass.prototype;20 SubClass.prototype.constructor = subclass;21 var Sub_one = new Subclass ("Zhangsan"), var sub_two = new Subclass ("Lisi"), Console.log (Sub_one), Console.log (Sub_two) ;

Finally, the print results of the instance objects Sub_one and Sub_two are posted.

    • Posted by Blog Park • Text top-Top Personal blog _ flower field half mu
    • Contact author brief book top Top Sina Micro Bow Wen Top
    • Original article, copyright notice: Free Reprint-Non-commercial-non-derivative-retain attribution | Top of the text

JS prototype chain (GO)

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.