ES6之前,因为没有extends继承,所以要想使用父构造函数中的属性,需要借用父构造函数继承属性。
子构造函数借用父构造函数继承属性:
因为是两个独立的构造函数,可以在子构造函数中调用父构造函数,调用过来后此时的this指向的是父构造函数的对象实例,因此需要用call()把this指向为子构造函数的对象实例。
// 父构造函数
function Father(uname,age){
this.uname = uname;
this.age = age;
}
// 子构造函数
function Son(uname,age,sex){
// 这时子构造函数想要使用父构造函数中的属性,要用到call()方法,同时把this更改为子构造函数的对象实例
Father.call(this,uname,age);
// 同时,子构造函数也可以有自己的属性
this.sex = sex;
}
// 创建子构造函数的对象实例
var son1 = new Son("Alice",21,"女");
console.log(son1);
子构造函数借用父构造函数继承方法:
/ 父构造函数
function Father(uname,age){
this.uname = uname;
this.age = age;
}
// 向父构造函数的原型中添加一个sing方法
Father.prototype.sing = function(){
console.log("我唱歌很好听~");
}
// 子构造函数
function Son(uname,age){
Father.call(this.uname,age);
}
// 相当于Son.prototype是父构造函数的实例
// 这样一来Son就可以使用父构造函数中的sing方法了
Son.prototype = new Father();
// 因为我们让Son.prototype = new Father(),所有要把Son的constructor指向Son本身
Son.prototype.constructor = Son;
// 此时Son已经可以使用Father里的方法了
var s1 = new Son("Ton",28);
console.log(s1); // 在__proto__的__proto__可以找到sing()方法
console.log(Son.prototype.constructor); // 指向的是Son