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

js prototype chain principle diagram explanation_javascript skills

WBOY
Release: 2016-05-16 17:51:59
Original
1208 people have browsed it

The inventor of ECMAscript designed this linked list in order to simplify the language while maintaining inherited properties. .
Have you ever learned about linked lists in data structures? There is a position in the linked list that is equivalent to a pointer, pointing to the next structure.

So the same goes for __proto__. Whenever you define a prototype, it is equivalent to pointing the __proto__ of the instance to a structure. Then the pointed structure is called the instance. prototype.

The text is a bit convoluted, look at the pictures to speak

Copy the code The code is as follows:

var foo = {
x: 10,
y: 20
};

Figure 1. A basic object with a prototype.


When I do not specify __proto__, foo will also reserve such an attribute.

If there is a clear pointer, then the linked list will be linked. La.

Obviously, b and c in the figure below share the attributes and methods of a, and at the same time have their own private attributes.

__proto__ also has pointing by default. It points to the highest-level object.prototype, and the __proto__ of object.prototype is empty.
Copy code The code is as follows:

var a = {
x: 10,
calculate: function (z) {
return this.x this.y z
}
};
var b = {
y: 20,
__proto__: a
};

var c = {
y: 30,
__proto__: a
};

// call the inherited method
b.calculate( 30); // 60

Figure 2. A prototype chain.


Understand the nature of the attribute link pointer __proto__. . Let’s understand constructor again.

When a prototype is defined, a prototype object will be constructed, and this prototype object is stored in the prototype method of the function that constructs the prototype.
Copy the code The code is as follows:

function Foo(y){
this.y = y ;
}

Foo. prototype.x = 10;

Foo.prototype.calculate = function(z){
return this.x this.y z;
};

var b = new Foo (20);

alert(b.calculate(30));

Figure 3. A constructor and objects relationship.

[Reference Document]

http://dmitrysoshnikov.com/ecmascript/javascript-the-core/
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!