JavaScript inheritance and prototype chain

Source: Internet
Author: User
Tags access properties hasownproperty

Because JS Foundation has been very poor, so I feel a lot of basic knowledge is not reliable, now take a moment to understand, although the completion of this post I may still not know, but the record at least I will again and again, and deepen the impression or get a different understanding of the present.

What is inheritance?

Often a lot of code after you have completed the construction, but also need to construct another similar function function; A lot of such examples are: vehicles/cars, Person/man, buildings/schools, etc.; personal understanding: Inheritance? Subclass inherits Parent class? One object to copy another object? Almost, it is easy to understand that the copy (overwrite) behavior between classes and classes, one object has properties and methods of another object. This also solves the idea and logic of how to implement inheritance.

What is a prototype chain?

A prototype? I simply understand that ===> Object.prototype is an attribute of an object, which is generally not visible (which can be __proto__ obtained in chrome), which we generally call it [[Prototype]] . Prototype chain? obj1.[[Prototype]]===> obj2.[[Prototype]] ===> ... obj3.[[Prototype]] . ===>Object.prototype。

inheritance based on the prototype chainInheritance Properties

The JS object is a dynamic property bag (with its own properties) and has a chain that points to a prototype object. When attempting to access the properties of an object, it searches not only on the object, but also on the prototype of the object, as well as the prototype of the object, and then layers up until it finds a property that matches the name or reaches the end of the prototype chain. As above.

Follow the ECMAScript standard, someobject. The [[Prototype]] symbol is a prototype used to point to someobject. An instance ofthe object created from ECMAScript 6new func () [[Prototype]]. The Object.prototype property represents the prototype object for object.

Give me a chestnut. (What happens when I try to access properties?) setting the property to an object creates its own properties. The only limit to getting and setting properties is the built-in getter or setter properties. ):

//Let's say we have an object o, which has its own properties A and B://{a:1, b:2}//the prototypes of O o.__proto__ have properties B and C://{b:3, c:4}//Finally, o.__proto__.__proto__ is null.//This is the end of the prototype chain, which is null,//by definition, NULL has no __proto__.//in summary, the entire prototype chain is as follows://{a:1, b:2}---> {b:3, c:4}---> NullConsole.log (O.A);//1//is a is O's own property? Yes, the value of this property is 1Console.log (O.B);//2//B is O's own property? Yes, the value of this property is 2//There is also a ' B ' property on the o.__proto__, but it will not be accessed. This is referred to as attribute masking (property shadowing).Console.log (O.C);//4//is c the self-attribute of O? No, let's see if there's any o.__proto__.//is C o.__proto__ 's own property? Yes, the value of this property is 4Console.log (O.D);//undefined//is d a self-attribute of O? No, let's see if there's any o.__proto__.//D is o.__proto__ 's own property? No, let's see if there's any o.__proto__.__proto__.//o.__proto__.__proto__ is null, stop the search,//no d attribute, return undefined
Inheritance Method

In JavaScript, any function can be added to an object as a property of an object. The inheritance of functions is no different from other property inheritance, including the above "Property overrides" (which is equivalent to the method overrides in other languages).

Note that when an inherited function is called, this refers to the currently inherited object, not the prototype object where the inherited function resides.

varn \{A:2, M:function(){    return  This. A + 1; }};console.log (O.M ()); //3//when O.M is called, ' this ' points to O.varp =object.create (o);//p is an object, p.__proto__ is O.P.a= 4;//Create the Self attribute of p a.Console.log (p.m. ());//5//when you call p.m., ' This ' points to p.//and because p inherits the M function of O//the ' this.a ' at this point is p.a, that is, P's own property ' a '
use different methods to create objects and build prototype chains

Here's a simple example of how you can understand

Normal
varo = {a:1};//o This object inherits all the attributes above the Object.prototype//so you can use O.hasownproperty (' a ') this way.//hasOwnProperty is the property of Object.prototype itself. //the Object.prototype prototype is null. //The prototype chain is as follows://o---> object.prototype---> NullvarA = ["Yo", "whadup", "?"];//arrays are inherited from Array.prototype//(IndexOf, foreach, and so on are inherited from it).//The prototype chain is as follows://a---> array.prototype---> Object.prototype---> Nullfunctionf () {return2;}//functions are inherited from Function.prototype//(call, bind, and so on are inherited from it)://f---> Function.prototype---> Object.prototype---> Null
Constructor (that is, new)

New is just a way of calling a function,

What's the difference between calling a function with new? New actually does three things:

    1. Create a new object
    2. Connect this new object to the top of the [[Prototype]] calling function prototype
    3. The binding invokes the function this and calls the

This can solve a lot of ideas, such as to give a simple and understandable chestnut:

function A () {} var b = {   show:function() {       Console.log ("This is show for B")    }} // How to make the __proto__ of object A and object B implement a inheritance B?  //A "constructor" of [[prototype]] Link ba.prototype == A; var New A ();// has been implemented in succession;a.show ();

Downstairs and upstairs do not contact, just give one more example

function Graph () {  this. Vertices = [];    this. Edges == {  function(v) {    this. Vertices.push (v);  }}; var New Graph (); // g is the generated object, and his own attributes are ' vertices ' and ' edges '. // when G is instantiated, g.__proto__ points to Graph.prototype.
object.create
varA = {a:1}; //a---> object.prototype---> Nullvarb =Object.create (a);//b---> A---> object.prototype---> NullConsole.log (B.A);//1 (inherited)varc =Object.create (b);//c---> B---> A---> object.prototype---> NullvarD = object.create (NULL);//d---> nullConsole.log (D.hasownproperty);//undefined, because D did not inherit Object.prototype
Impersonation class inheritance
/** * Achieve A Succession B*/functionB (b) { This. B =B}functionA (A, b) {//call B and bind thisB.call ( This, B) This. A =A} A.prototype=object.assign ({}, B.prototype) A.prototype.constructor=Avarc =NewA (1, 2) Console.log (C.A)//1//C has a B attribute that only the instance of B hasConsole.log (C.B)//2

JavaScript inheritance and prototype chain

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.