It has been 1485 days since the last update, the content of the article may be outdated.

原型继承

c++,python,java继承的本质是扩展一个已有的Class,并生成新的Subclass。JavaScript由于采用原型继承,我们无法直接扩展一个Class,因为根本不存在Class这种类型。

JavaScript 的原型继承实现方式:

  • 定义新的构造函数,并在内部用 call() 调用希望“继承”的构造函数,并绑定 this

  • 借助中间函数 F 实现原型链继承,最好通过封装的 inherits 函数完成;

  • 继续在新的构造函数的原型上定义新方法。

inherits 方法构造

javascript
function inherits(Child,Parent){
var F=function(){};
F.prototype=Parent.prototype;
Child.prototype=new F();

Child.prototype.constructor=Child;

}

//实例

function Student(props){
this.name=props.name || 'unnamed';
}

Student.prototype.Hello=function(){
alert( "Hello "+this.name);
}

function primaryStudent(props){
call Student(this,props);
this.grade=props.grade;
}

inherits(primaryStudent,Student);

primaryStudent.prototype.getgrade=function(){
return this.grade;
}