preface
Prototype and prototype chain are important concepts in JS, so let’s understand the following four rules for reference types:
- Reference types, which have object properties and can extend properties freely.
- All reference types have an implicit stereotype
__proto__
Property, the property value is a normal object. - Reference types, implicit archetypes
__proto__
The property value points to the explicit prototype property value of its constructor. - When you try to get a property of an object, if the object doesn’t have the property itself, it will get rid of its implicit stereotype
__proto__
(that is, the explicit prototype of its constructor).
Reference types: Object, Array, Function, Date, RegExp. Here I’ll just call __proto__ implicit, there is no official Chinese name, most people call it blind.
You can freely extend properties
Reference types, all of which have object properties that can be extended freely:
const obj = {}
const arr = []
const fn = function () {}
obj.a = 1
arr.a = 1
fn.a = 1
console.log(obj.a) / / 1
console.log(arr.a) / / 1
console.log(fn.a) / / 1
Copy the code
This rule should be easy to understand, as should Date and RegExp.
__proto__
attribute
Each reference type has an implicit prototype __proto__ attribute whose value is an ordinary object:
const obj = {};
const arr = [];
const fn = function() {}
console.log('obj.__proto__', obj.__proto__);
console.log('arr.__proto__', arr.__proto__);
console.log('fn.__proto__', fn.__proto__);
Copy the code
__proto__
And the prototype
Reference type, the implicit prototype __proto__ property value points to the explicit prototype property value of its constructor:
const obj = {};
const arr = [];
const fn = function() {}
obj.__proto__ == Object.prototype // true
arr.__proto__ === Array.prototype // true
fn.__proto__ == Function.prototype // true
Copy the code
Look for properties or methods
When you try to get a property of an object, if the object doesn’t have the property itself, it will look in its implicit prototype __proto__ (that is, the explicit prototype of its constructor) :
const obj = { a:1 }
obj.toString
ƒ toString() {[native code]}
Copy the code
First, obj does not have a toString attribute. The toString attribute can be obtained by following the fourth rule, which is derived from the prototype constructor Object.
Prototype chain
function Person(name) {
this.name = name
return this // This object is returned by default
}
var nick = new Person("nick")
nick.toString
ƒ toString() {[native code]}
Copy the code
Nick is an instance of the Person constructor, and Person’s prototype doesn’t have a toString method. Here comes the concept of prototype chain. The Nick instance first reviews itself and finds that there is no toString method. If not, go up and look for the Prototype property of the Person constructor. Constructor: toString (); constructor: toString (); toString ();