# 6.构造函数与原型继承
ES6之前,并没有提供 extends 继承,但是可以通过构造函数+原型对象的方式模拟实现继承,这种继承方式被称为组合继承
# 1.call()
调用某个函数,并且修改函数运行时this的指向
fun.call(thisArg, arg1, arg2)
thisArg:当前调用函数this的指向对象
arg1,arg2:传递的其他参数
function fn() {
console.log('1111')
console.log(this)
}
// call()可以调用函数
fn.call()
// call() 可以修改this的指向
let obj = {
name: '张三'
}
fn.call(obj)
# 2.借用构造函数继承父类型属性
核心原理:通过call()把父类型的this指向子类型的this,这样就可以实现子类型继承父类型的属性
function Person(name){
this.name = name
}
function Student(name, subject) {
// 借用父构造函数,并且调整父构造函数的this指向
Person.call(this,name)
this.subject = subject
}
let zhangsan = new Student('张三', '犯罪心理学')
console.log(zhangsan)
# 3.借用构造函数继承父类型方法
Person.prototype.drink = function () {
console.log('喝水')
}
console.log(zhangsan)
// 会发现,并没有继承到父类型的方法
Student.prototype = Object.create(Person.prototype)
// Student.prototype = new Person.prototype
// 为什么不可以 直接 = Person.prototype?
// 这样子两者直接指向同个原型对象,导致子类修改方法时也会修改父类
// 然后重新指向构造函数
Student.prototype.constructor = Student