#### 原型
- 构造函数:只有函数都有prototype属性对象
- 原型:构造函数有一个prototype属性,是一个对象,即原型对象。Person.prototype
- 实例:实例的__proto__属性指向对象原型的指针。 person.__proto__ === Person.prototype
- contrucotr属性:constructor是原型指向构造函数的指针。Person.prototype.constructor === Person
// 构造函数
function Person() {
}
// 在构造函数的原型添加方法
Person.prototype.addName = function(name) {
this.name = name
}
// 实例
const person = new Person()
Person.constructor === Person
Person.prototype.constructor === Person
person.__proto__ === Person.prototype
Person.prototype.__proto__ === Object.prototype
Object.prototype.constructor === Object
#### 原型链
- 如果原型对象是另一个类型的实例,这个类型的原型又是另一个类型的实例,层层递进, 构成实例和原型的链条
- 查找一个对象的属性时,先查找自身的属性,然后查找原型,然后再查找原型的原型,一直往上,直到Object.prototype,如果没有则返回null
function Top() {}
function Parent() {}
function Person() {}
Top.prototype.setAge = function(age) {
this.age = age
}
Parent.prototype = new Top()
Parent.prototype.setName = function(name) {
this.name = name
}
Person.prototype = new Parent()
const person = new Person()
person.setName('hello') // person.name hello
person.setAge(18) // person.age 18