supplement
- By default, the display prototype of the function points to an empty Object instance Object.
var fn = new Fn()
console.log(Fn.prototype instanceof Object) // false
console.log(Object.prototype instanceof Object) // false
console.log(Function.prototype instanceof Object) // true
Copy the code
- All functions are instances of Function (including Function)
console.log(Function.__proto__ === Function.prototype) // true
Copy the code
- An Object is the end of the prototype chain
console.log(Object.prototype.__proto__) // null
Copy the code
Attribute problem of prototype chain
- When reading the property value of an object: it is automatically looked up in the prototype chain
function Fn() {
}
Fn.prototype.a = 'xxx'
var fn1 = new Fn()
console.log(fn1.a) // xxx
Copy the code
- When setting the value of an object’s property: The stereotype chain is not looked up. If the property is not present in the object, the property is added and its value is set
function Fn() {
}
Fn.prototype.a = 'xxx'
var fn1 = new Fn()
var fn2 = new Fn()
fn2.a = 'yyy' // Add the property a directly and set its value to YYy
console.log(fn1.a) // xxx
console.log(fn2.a) // yyy
Copy the code
- Methods are defined in stereotypes, and properties are defined on the object itself via constructors
function Person(name, age) {
this.name = name
this.age = age
}
Person.prototype.setName = function (name) {
this.name = name
}
var p1 = new Person('Tom'.18)
p1.setName('Bob')
console.log(p1.name, p1.age) // Bob 18
var p2 = new Person('Jack'.18)
p2.setName('Andy')
console.log(p2.name, p2.age) // Andy 18
console.log(p1.__proto__ === p2.__proto__) // true implicit prototype consistency
Copy the code