Javascript 使用原型来实现类的继承。在ECMAScript6 引入class的概念也是原型继承的语法糖
1. 原型基于构造函数
// 定义Person构造函数
function Person(name, age) {
// 自有属性
this.name = name
this.age = age
}
2. 构造函数自带一个属性prototype,称之“原型”。
prototype也是对象,默认包含constructor属性和 [[proto]]属性
console.log(Person.prototype);

3. 在原型上添加函数,能被所有Person实例访问,只有一份
(定义在构造函数内的函数在构造多个实例时则有多份)
Person.prototype.sayName = function() {
console.log(this.name)
}
console.log(Person.prototype);

4. new 一个实例
proto 是默认指向其构造函数原型属性的指针
kitty通过proto可以搜索到Person.prototype上定义的属性
let kitty = new Person('kitty', 10)
console.log(kitty.__proto__ === Person.prototype) // true
5. 原型链搜索过程:先此对象自身属性上查找,再去它的[[proto]]指向的原型上查找,
如果也没找到,则继续在构造函数的原型(prototype)的[[proto]]上查找,一层层向上查找直到Object.prototype
console.log(Object.prototype.__proto__ === null) //true
function Person(name, age) {
let priAttr = 'owner'
this.name = name
this.age = age
this.sayAttr = function() {
console.log(priAttr)
}
}

sayName()添加在Person原型上。 sayAttr()添加在Person构造函数中
6. 借用构造函数+原型链的组合继承方法
function Student(name, age, grade) {
// 借用构造函数,继承Person的自有属性
Person.call(this, name, age)
this.grade = grade
}
// Object.create创建Person.prototype空对象,继承原型上方法
Student.prototype = Object.create(Person.prototype)
// 修改constructor指向
Student.prototype.constructor = Student
let tom = new Student('tom', 11, 4)
console.log(kitty instanceof Person, tom instanceof Student)
console.log(tom)

网友评论