javascript的原型继承的实现:
1.定义新的构造函数,并在内部使用call()调用希望继承的构造函数,并指向this;
2.借用中间空函数F实现原型链继承;
3.将新构造函数原型指向一个新的F对象,再将新构造函数原型的构造函数修复为新构造函数;
4.继续在新构造函数的原型上定义新方法。
举例:
function Student(props){
this.name = props.name||"未知";
}
Student.prototype.hello = function(){
return "Hello,"+this.name;
}
function PrimaryStudent(props){
Student.call(this,props);
this.grade = props.grade||1;
}
function extend(child,parent){
var F = function(){};//空函数
F.prototype = parent.prototype;//将F的原型指向希望继承的构造函数的原型
child.prototype = new F();//将新构造函数的原型指向一个新的F对象
child.prototype.construct = child;//将新构造函数原型的构造函数修复为新构造函数
}
extend(PrimaryStudent,Student);
PrimaryStudent.prototype.getGrade = function(){
return this.grade;
}
var xiaoming = new PrimaryStudent({name:"小明"});此时,xiaoming对应的原型链如下图:
//校验原型
xiaoming.__proto__ === PrimaryStudent.prototype;//true
xiaoming.__proto__.__proto__ === Student.prototype;//true
//验证继承关系
xiaoming instanceof PrimaryStudent;//true
xiaoming instanceof Student;//true以上。
学习链接:原型继承 - 廖雪峰的官方网站
版权声明:本文为guishifoxin原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。