function Person(name) {
this.name = name;
this.getName = function(){
return this.name;
};
}
function Student(name,score) {
this.newPerson = Person;
this.newPerson(name);
delete this.newPerson;//赋值之后一定要删掉,避免多重继承时导致的属性,方法覆盖
//Person.call(this, name);//同上等价
//Person.apply(this, arguments);//同上等价
this.score=score;
this.getScore=function(){
return score;
};
}
以上的代码是通过对象冒充来实现的继承(也可通过call和apply方法替代来达到同样的结果)
这种方法依赖内部构造器,Person添加到prototype下面的方法或属性都将无法继承到
根据上面的写法我们很容易就可以想到他可以继承多个类
再看下面这种方法
function Person(name) {
this.name = name;
this.getName = function(){
return this.name;
};
}
function Student() {
}
Student.prototype = new Person();
Student.prototype.score = '';
Student.prototype.getScore = function() {
return this.score;
}
这是通过给原型链赋值来达到继承的目的的,很显然这种方法只能继承一个类,多个的话直接会被最新的覆盖掉
虽然他会继承到父类中所有的属性,但他无法通过构造器进行赋值,也就是说只能通过手动从Student.prototype中找到对应的属性
赋值,这并不是我们想要的结果
因此就出现了混合继承(将两者合二为一)
function Person(name) {
this.name = name;
this.getName = function(){
return this.name;
};
}
function Student(name,score) {
Person.call(this, name);
this.score = score;
}
Student.prototype = new Person();
Student.prototype.getScore = function () {
return this.score;
}
以此来达到上面两种继承的合并