The prototype chain is a mechanism, which means that each object in JavaScript, including the prototype object, has a built-in [[proto]] attribute that points to the prototype object of the function object that created it, that is, the prototype attribute.
Function: The existence of the prototype chain is mainly to realize the inheritance of objects.
Several concepts about the prototype chain:
1. Function object
In JavaScript, functions That is the object.
2. Prototype object
When defining a function object, it will contain a predefined attribute called prototype, which is called the prototype object.
//函数对象 function F(){}; console.log(F.prototype)
3, __proto__
When JavaScript creates an object, there will be a [[proto]] built-in attribute. A prototype used to point to the function object that created it. Prototype objects also have [[proto]] attributes. Therefore, in constant pointing, a prototype chain is formed.
For example, if we modify the prototype object of object F, we can clearly see the above relationship
//函数对象 function F(){}; F.prototype = { hello : function(){} }; var f = new F(); console.log(f.__proto__)
4 , new
When using new to call the constructor, it is equivalent to executing
var o = {}; o.__proto__ = F.prototype; F.call(o);
Therefore, new plays a key role in the implementation of the prototype chain.
5. Constructor
The prototype object prototype has a predefined constructor attribute, which is used to reference its function object. This is a circular reference.
function F(){}; F.prototype.constructor === F;
In actual application, the following writing method is often used
function F(){}; F.prototype = { constructor : F, doSomething : function(){} }
The reason why constructor is added here is because the prototype object is rewritten, and the constructor attribute disappears, and you need to manually fill it in.
6. Memory structure of prototype chain
function F(){ this.name = 'zhang'; }; var f1 = new F(); var f2 = new F();
The above is the detailed content of What is js prototype chain. For more information, please follow other related articles on the PHP Chinese website!