Home > Web Front-end > JS Tutorial > body text

What is js prototype chain

little bottle
Release: 2019-05-31 10:45:00
Original
15877 people have browsed it

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.

What is js prototype chain

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)
Copy after login

What is js prototype chain

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__)
Copy after login

What is js prototype chain

4 , new

When using new to call the constructor, it is equivalent to executing

var o = {};
o.__proto__ = F.prototype;
F.call(o);
Copy after login

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;
Copy after login

In actual application, the following writing method is often used

function F(){};
F.prototype = {
    constructor : F,
    doSomething : function(){}
}
Copy after login

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();
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template