原型对象及原型链

原型对象

每个函数都具有一个 prototype 属性,这个属性是一个指针,指向一个对象(即原型对象)。
原型对象的用途是为每个实例对象存储共享的方法和属性。

instanceof 方法:测试构造函数的 prototype 属性是否出现在对象的原型链中的任何位置。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
function Person() {}

Person.prototype.name = 'wzp'
Person.prototype.age = 25
Person.prototype.say = function() {
console.log(this.name)
}

var me = new Person()

me instanceof Person // true

console.log(Person.prototype)
// => prototype (原型对象)值:
Person.prototype = {
name: 'wzp',
age: 25,
say: f(),
constructor: f Person(), // 构造函数本身
__proto__: Object // Object.prototype
}

// 如果重写原型对象
Person.prototype = {
name: 'wzp',
age: 25
}
// 那么
Person.prototype.constructor === Object
// 需要手动设置其 constructor
Person.prototype.constructor = Person

me instanceof Person // false

Person 构造函数、Person 原型属性 和 Person 实例之间的关系

构造函数的 prototype 属性 和 实例的 __proto__ 属性都是指向 原型对象(prototype),共享其属性和方法,即:Person.prototype === me.__proto__

原型链

当读取实例的属性时,如果找不到,就会查找与对象关联的原型中的属性,如果还查不到,就去找原型的原型,一直找到最顶层为止。

1
2
3
4
5
6
7
8
9
10
11
12
13
function Person() {}

Person.prototype.name = 'wzp'

var me = new Person()
me.name = 'may'
console.log(me.name) // 'may'

delete me.name
console.log(me.name) // 'wzp'

delete Person.prototype.name
console.log(me.name) // undefined
0%