When a function is created, a property called prototype is generated. If we create an instance object using the current function as a constructor, the instance object will have an implicit [[prototype]] pointer to the constructor’s Prototype property. That’s the prototype for this instance object.
If the prototype of the current instance object is also an instance of a type, then that prototype also has an implicit [[prototype]] pointing to another prototype, and so forth, forming a prototype chain. For example, if we simply create a new function:
function A() {
this.name = 'mysteryven'
}
A.prototype.sayName = function() {
console.log(this.name);
}
Copy the code
We use the A function to create an instance, so we have:
const a = new A();
a.__proto__ === A.prototype;
A.prototype.__proto__ === Object.prototype;
Object.prototype.__proto__ === null;
Copy the code
In a prototype object, there is a constructor attribute that points to the constructor by default, as in our built-in Function:
Function.prototype.constructor === Function
Copy the code
However, sometimes when we set a prototype we assign the prototype directly to another object like this:
A.prototype = {
sayName: () => {}
}
Copy the code
This results in incorrect orientation of constructor. For this case, we need to set the following additional Settings:
A.prototype = {
constructor: A,
sayName: () = >{}}Copy the code
At this point, pointing is fine, but we’ll find that we can use for… in… Traverse to the constructor property:
The reason is that JS’s built-in constructor is not enumerable. Here we add a constructor attribute to the prototype object, and without doing any additional processing, it becomes enumerable. This is not what we want. To do this, we set it like this:
Object.defineProperty(
A.prototype,
'constructor',
{
enumerable: false.value: A
}
)
Copy the code
In Google Chrome, we can access the prototype of the instance Object via its __proto__ property, but this is not a standard implementation and may be deprecated in the future, preferably via Object.getPrototypeof ().