Inheritance and prototype chain in Javascript

Source: Internet
Author: User
Tags inheritance

In programming languages, objects are not as ubiquitous as they are in the real world. We usually only have a few native objects, and the rest should be created by ourselves. In Java, this is what we do when we create a cool chicken:

Public class Chicken {
 
Public void makeSound (){
 
System. out. println ("giggling ");
 
}
}
Chicken littleChicken = new Chicken ();

Define a Chicken class, describe many of its characteristics in the Chicken, and then create a new littleChicken based on these descriptions.

This is a method to generate objects in a class-centered programming language, like creating a mold first and then casting a mold according to the mold. Another idea is to copy the most primitive and basic object that already exists, and then repair and supplement it on the new object. The original object is the prototype, it is the idea of prototype programming. It represents the language, that is, Javascript.

For example:

Var Chicken = function (){
This. sound = "giggling ";
};
Chicken. prototype = {
Bark: function () {alert (this. sound )}
};
Var littleChicken = new Chicken ();

Is it very similar to the method that just defined the class, that is, defining the class first and then adding an object according to the class new. In fact, the principle is very different. Start with the prototype.

In Javascript, all objects are inherited from Object. prototype. It looks like an ancestor-level Object. Why is Object. prototype not inherited from Object? Because Object is actually a constructor and constructor, it is similar to the existence of classes in Java. It is like a high-tech machine used to copy a prototype. What about templates in high-tech machines? It has already been put into the machine. It is the prototype of the machine, that is, Object. prototype. When talking about objects, we are actually talking about the high-tech machine, Object. prototype, which is the prototype of the proxy machine.

The Chicken in the above code is a custom constructor. When we use this constructor to create an object, we actually use this constructor to clone the template in it, that is, prototype. The constructor is actually a common function in which we use this for some configuration. This refers to the object to be created, and prototype is the template placed on the machine. When we use the Chicken constructor to create a new object, it is equivalent to copying the Chicken. prototype: create a new object, add a sound attribute to the new object, and assign a "giggle" value to it ".

Console. log (Object. getPrototypeOf (littleChicken); // Object {} bark: () _ proto __: Object

Object. getPrototypeOf is a function used to obtain the Object prototype. The output represents an Object with a bark function. Is it the same as Chicken. prototype? The following _ proto __: Object represents the prototype of the prototype, that is, Object. prototype. The first Object represents a common Object, and the second Object represents the constructor, as follows:

Console. log (Object. getPrototypeOf (Object. getPrototypeOf (littleChicken); // Object {}

Simply put:

1. All objects are copied from another object. The copied object is called the "prototype" of the new object"
2. The tool used to complete the copy operation is called the constructor. The constructor is a common function. Configure the prototype for the constructor"
3. by calling Object. getPrototypeOf () or object. _ proto _ can obtain the prototype of this object. According to the ECMAScript standard, someObject. [[Prototype] indicates the Prototype used to assign a someObject.
4. All prototypes are inherited from Object. prototype
5. Object. prototype inherits from null. That is, the end of the prototype chain is null.


JavaScript: my understanding of prototype chain

The prototype chain has always been a very abstract concept and cannot be found. With the recent study of JavaScript, I have a little understanding of the prototype chain.

Basic knowledge

In JavaScript, there are two types of values: original value and object value. each object has an internal attribute [[prototype], which is usually called a prototype. the prototype value can be an object or null. if its value is an object, the object must have its own prototype. in this way, a linear chain is formed, which is called the prototype chain.

You can use the Object. getPrototypeOf method in ES5 or the _ proto _ attribute in ES6 to access the prototype of an Object.

The role of prototype chain is to implement inheritance. For example, if we create an array, the array method is inherited from the prototype of the array.

Var arr = [];
Arr. map = Array. prototype. map // arr. map is from arr. inherited from _ proto _, arr. _ proto _ is Array. prototype

Graphical prototype chain

Although we all talk about prototype chain, in fact, when the js engine is running, it does not consider frame in the webpage, all existing objects constitute a prototype tree. by default, there is only one tree. the root node can be called an Object. prototype, or null.

However, we can create another prototype tree by using the Object. create method.

Var foo = Object. create (null); // foo is an Object, but it is free and does not belong to the existing prototype tree.
Var bar = Object. create (foo); // The prototype of bar is foo.
Var baz = Object. create (foo); // The prototype of baz is foo.

So we have the second prototype tree.

Traverse prototype chain

We have no way to traverse all objects whose prototype is an object, but we can traverse up to obtain all the upper-layer prototype of an object. This prototype chain must be linear, the end is null.

Function getPrototypeChain (object ){
Var protoChain = [];
While (object = object. _ proto __){
ProtoChain. push (object );
    }
ProtoChain. push (null );
Return protoChain;
}

The display format varies depending on different environments. The following is the display in the chrome console.

> GetPrototypeChain (new String (""))
[String, Object, null] // String. prototype, Object. prototype, null
 
> GetPrototypeChain (function (){})
[Function Empty () {}, Object, null] // Function. prototype, Object. prototype, null

The prototype chain of the built-in type object is not long. Next, try the host object.

> GetPrototypeChain (document. createElement ("div "))
[HTMLDivElement, HTMLElement, Element, Node, Object, null]

This is much longer.

Super-long prototype chain

We can see that the objects we normally use do not have a long prototype chain, but we can construct one by ourselves.

Function Foo (){}

For (var I = 0; I <100; I ++ ){
Foo. prototype ["foo" + I] = I;
Foo. prototype = new Foo;
}
Console. dir (getPrototypeChain (new Foo ));

How many upper-layer prototypes does the new Foo last have?

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.