5.4.7. Prototype chain¶
5.4.7.1. Explicit and Implicit Prototypes¶
JavaScript prototypes are divided into explicit prototypes (explicit prototype property) and implicit prototypes (implicit prototype link).
The explicit prototype refers to the prototype, which is an attribute of the function. This attribute is a pointer, pointing to an object, showing the attribute of modifying the prototype of the object. Only functions have this attribute.
Implicit prototype refers to the built-in property prototype that any object in JavaScript has. There was no standard way to access this built-in property prior to ES5, but most browsers support via __proto__
to access . ES5 has a standard Get method for this built-in property Object.getPrototypeOf()
.
The implicit prototype points to the prototype of the function (constructor) that created the object, which __proto__
points to the prototype object of the current object, and the prototype points to the prototype object of the object constructed with the current function as the constructor.
The role of explicit prototypes is used to implement prototype-based inheritance and property sharing. Implicit prototypes are used to form prototype chains, and are also used to implement prototype-based inheritance. For example, when we access the x property in the obj object, if it is not found in obj, then it will be searched __proto__
in turn .
Note: Object.prototype This object is an exception, its __proto__ value is null
5.4.7.2. The new process¶
var Person = function(){};
var p = new Person();
The process of new is divided into the following three steps:
var p={};
Initialize an object pp.__proto__ = Person.prototype;
Person.call(p);
Construct p, which can also be called initialization 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 will return true. Explain that our step 2 is correct.
5.4.7.3. Examples¶
var Person = function(){};
Person.prototype.sayName = function() {
alert("My Name is Jacky");
};
Person.prototype.age = 27;
var p = new Person();
p.sayName();
p is an object that references a Person. We define a sayName method and age attribute on the prototype of Person. When we execute p.age, we will first look inside this (that is, inside the constructor), and if not found, we will go back up the prototype chain.
How is the upward traceback here? Here we use the __proto__
property to link to the prototype (that is, Person.prototype) for lookup. Finally found the age property on the prototype.
5.4.7.4. Prototype chain pollution¶
As mentioned earlier, JavaScript is dynamic inheritance, by __proto__
modifying own object will affect the object with the same prototype. Therefore, when the key-value pair is user-controllable, prototype chain pollution may occur.