This article mainly introduces the understanding of the javaScript prototype chain, and makes an easy-to-understand analysis of the concept and related usage skills of the javaScript prototype chain in the form of examples, you can refer to the examples in this article to describe the prototype chain of javaScript. Share it with you for your reference. The specific analysis is as follows:
I used to think that the javascript prototype chain is a very deep thing and I have never understood it very well. After reading some introductions today, I found this figure, it means that no language can be clearer than this figure.
After reading this figure, I suddenly had a qualitative understanding of javascript.
The prototype chain of javascript has two types: explicit and implicit:
Explicit prototype chain:That is, our common prototype;
Implicit prototype chain:In general environments, access is unavailable, that is, invisible. In FireFox, access is allowed through _ proto _. The implicit prototype chain is used for the search of the prototype chain inside the javascript engine, set by displaying the prototype chain;
1. Concepts of prototype and _ proto _
Prototype is a function attribute (each function has a prototype attribute). This attribute is a pointer pointing to an object. It displays the attributes of the modified object prototype.
_ Proto _ is the built-in property of an object (Note: prototype is the built-in property of the function, __proto _ is the built-in property of the object ), is the property of the prototype chain used inside JS.
Chrome and FF can be used to access the _ proto _ attribute of the object. IE cannot.
Ii. new Process
var Person = function(){};var p = new Person();
The new process is split into the following three steps:
(1) var p = {}; that is, initializing an object p
(2) p. _ proto _ = Person. prototype;
(3) Person. call (p); that is to say, Constructing p can also be called initializing p.
The key lies in the second step. Let's prove it:
var Person = function(){};var p = new Person();alert(p.__proto__ === Person.prototype);
This code returns true. It indicates that step 2 is correct.
Iii. Example
var Person = function(){};Person.prototype.sayName = function() { alert("My Name is Jacky");};Person.prototype.age = 27;var p = new Person();p.sayName();
P is a reference object pointing to Person. We define a sayName method and age attribute in the prototype of Person. When we execute p. age, it first searches inside this (that is, inside the constructor), if it is not found, and then traces it up along the prototype chain.
How is the upward tracing going up here? Here we need to use the _ proto _ attribute to link to the prototype (that is, Person. prototype) for search. Finally, the age attribute is found in the prototype.
I hope this article will help you design javascript programs.