JS通过prototype实现继承的简单示例:
var MYJS={};
MYJS.extend=function(baseClass, prop) {
if (typeof (baseClass) === "object") {
prop = baseClass;
baseClass = null;
}
// 本次调用所创建的类(构造函数)
function F() {
}
// 如果此类需要从其它类扩展
if (baseClass) {
F.prototype = new baseClass();
F.prototype.constructor = F;
}
// 覆盖父类的同名函数
for (var name in prop) {
if (prop.hasOwnProperty(name)) {
F.prototype[name] = prop[name];
}
}
return F;
};
使用示例:
<script>
function Cls1(){
this.name="Cls1 class";
this.fun1 =function(){
console.log("Cls1.fun1");
};
}
var Cls2 = MYJS.extend(Cls1,
{
a:'a',
fun2:function(){
console.log("Cls2.fun2");
}
});
var Cls3 = MYJS.extend(Cls2,
{
a:'cls3.b',
b:'b',
fun3:function(){
console.log("Cls3.fun3");
}
});
var obj3 = new Cls3();
console.log(obj3.name);
console.log(obj3.a);
console.log(obj3.b);
obj3.fun1();
obj3.fun2();
obj3.fun3();
</script>