The prototype

Explanation: A prototype is a pioneering model that represents the same type of person, object, or idea (Wikipedia). In javascript, a prototype is a model of an object when it is created, with common properties and behaviors (methods) of the same class of objects.

Prototype object

In JS every function has a property that points to a prototype — prototype, called a prototype object. The stereotype object has a property called constructor that points to the constructor. Functions here include not only constructors, but also ordinary functions.

  • Stereotype objects have public properties and methods
  • Js inheritance is based on prototype objects
function Fn (name) {
  this.name = name
}
console.log(Fn.prototype)
Fn.prototype.constructor === Fn //true
Copy the code

Prototype chain (PROTO)

In JS, every object (except null) has a __proto__ attribute, which refers to the protoobject. In other words, the object inherits properties and methods from that protoobject, which can be found by this attribute. The prototype chain is implemented based on __proto__. When we visit the attribute of an object or method, will go to the object itself to find this property or method, if not found, is to find its prototype object, if the prototype object is not found, will be up to the prototype object of a prototype object, by analogy, find it returns the value of the corresponding Returns undefined if the prototype object is not found until it is null.

function Fn(name) {
  this.name = name
}
Fn.__proto__ === Fn.prototype // true
Fn.__proto__.__proto__ ===  Fn.prototype.__proto__ === Object.prototype // rue
Objcet.prototype.__proto__ === null // rue
Copy the code

Every js object has a __proto__ attribute. If a function is an object, then it has a __proto__ attribute. right Which prototype object does the function’s __proto__ point to? The instance’s __proto__ points to the constructor’s prototype. Object, Function, and other js constructors are essentially instances of the Function constructor

function Fn(name) {
  this.name = name
}
Fn.__proto__ === Function.prototype
Object.__proto__ === Function.prototype // true
Function.__proto__ === Function.prototype // true
Array.__proto__ === Function.prototype // true
Copy the code

supplement

  • Objects created by Object.create(null) have no prototype objects

conclusion

  • Js objects are always created with an object — prototype
  • Js objects inherit properties and behaviors (methods) by building prototype chains through __proto__ attributes
  • The __proto__ of all instances points to the prototype object of their constructor
  • The top level of the prototype chain is NULL.