Article Directory
Prototype and Prototype Chain
Prototype
Function prototype property
- Each function has a prototype attribute, which by default points to an Object empty object (ie prototype object)
console.log(Date. prototype, typeof Date. prototype )
function fun () {
}
console.log (fun.prototype) //默认指向一个空Object对象
- There is a property constructor in the prototype object, which points to the function object
console.log(Date.prototype.constructor===Date )
console.log(fun.prototype.constructor===fun)
Add properties to the prototype object
- All instance objects of the function automatically have the properties in the prototype
fun.prototype.test = function () {
console.log('test()')
}
Explicit and implicit prototypes
Explicit prototype
Every function function has a prototype property, which is an explicit prototype
Implicit prototype
Each instance object has a _ _ proto _ _ property, which is the implicit prototype
Relationship difference
- The value of the implicit prototype of the object is the value of the explicit prototype of its corresponding constructor
- The explicit prototype is automatically added when the function is defined, and the default value is an empty Object object
- The implicit prototype _ _ proto _ _ is automatically added when the instance object is created, and the default value is the prototype property value of the constructor
Prototype chain (implicit prototype chain)
Role:
find the properties of the object (method)
When we are accessing the properties of an object, the search order of the properties:
- First search in its own properties, find and return
- There is no own property, look up along _ _ proto _ _ (implicit prototype chain), find and return
- The prototype chain has reached the end and still not found, return undefined
Reference materials, B station is still Silicon Valley JavaScript advanced tutorial.