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>