这两个方法,已经讲过,是调用函数的,当然也能调用构造函数
function Person(newId,newName){
this.id = newId;
this.name = newName;
}
function Student(newId,newName,newScore){
//借用构造方法
Person.call(this,newId,newName);
this.score = newScore;
}
let student = new Student("007","老王",99);
console.log(student.id,student.name,student.score);
但是这样的继承的方式也有弊端:
1.无法继承父类原型上的属性和方法
2.单独使用这种借用的模式,所有要继承的属性和方法都要在父类型的构造函数里定义,
特别是实例共享的属性和方法也写在构造函数里,那么这样会浪费内存。所以,很少很少单独使用
//如:
function Person(newId,newName){
this.id = newId;
this.name = newName;
}
Person.prototype.eat = function(){
console.log("Person eat");
}
function Student(newId,newName,newScore){
//借用构造方法
Person.call(this,newId,newName);
this.score = newScore;
}
let student = new Student("007","老王",99);
console.log(student.id,student.name,student.score);
student.eat();//报错
必须改成以下形式
function Person(newId,newName){
this.id = newId;
this.name = newName;
this.eat = function(){
console.log("Person eat");
}
}
function Student(newId,newName,newScore){
//借用构造方法
Person.call(this,newId,newName);
this.score = newScore;
}
let student = new Student("007","老王",99);
console.log(student.id,student.name,student.score);
student.eat();
组合继承:
结合前两种方式:原型链式继承和Call()/Apply()方式继承,我们就能解决前面提出的那些问题。
利用原型链继承共有的属性和方法,利用Call/Apply来初始化自己的但是和父类型同名的属性或方法。
function Person(newId,newName){
this.id = newId;
this.name = newName;
}
Person.prototype.eat = function(){
console.log("Person eat");
}
function Student(newId,newName,newScore){
Person.call(this,newId,newName);
this.score = newScore;
}
Student.prototype = new Person();
let student = new Student("007","老王",99);
console.log(student.id,student.name,student.score);