es6 之前并没有给我们提供extends 继承。我们可以通过 构造函数+原型对象模拟实现继承,被称为组合继承
1. call()
调用这个函数,并且修改函数运行时的 this指向
fun.call(thisArg,arg1,arg2,...)
- thisArg:当前调用函数this 的指向对象
- arg1,arg2:传递的其他参数
2. 借用构造函数继承父类型属性
核心原理: 通过call() 把父类型的this 指向子类型的this,这样就可以实现子类型继承父类型的属性
//1. 父构造函数
function Father(uname, age) {
// this 指向父构造函数的对象实例
this.uname = uname;
this.age = age;
}
//2. 子构造函数
function Son(uname, age, score) {
// this 指向子构造函数的对象实例
Father.call(this, uname, age); // 这个this 指向的是 子构造函数的对象实例
this.score = score;
}
var son = new Son('ldh', 18, 100);
console.log(son);
3. 借用原型对象继承父类型方法
Son.prototype = new Father();
//如果利用对象的形式修改了原型对象,别忘了用constructor指回原来的构造函数
Son.prototype.constructor = Son;