[英]Issues with Javascript inheritance & base class prototype
我在繼承時遇到配置對象的問題,所以我已經
baseclass.prototype.activity =function(){ console.log("Im"+activity); }
以及其他繼承基類的其他對象(例如A和B)。
我想根據A和B的類型配置運行,因此,如果它是A,則調用run應該將活動設置為Running,並且與B類似,它可能會游泳我正在使用以下工廠方法根據類型創建A和B
activityFactoryObject.prototype.makeObj = Object.create(baseclass);
activityFactoryObject.prototype.createObject = function (config) {
switch (config) {
case "running":
this.makeObj = A;
break;
case "swimming":
this.makeObj = B;
break;
}
this.makeObj.prototype = baseclass.prototype;
return new this.makeObj(config);
};
我不確定您的目標是什么,但是如果它們都從baseClass繼承而來,唯一的區別是活動顯示的內容就足夠了:
baseClass.protoype.activity = function ( activity ) { console.log( "I'm " + activity ); };
var a = new BaseClass(),
b = new BaseClass();
a.activity( 'Running' ); // -> "I'm Running"
b.activity( 'Swimming' ); // -> "I'm Swimming"
不確定這是否是您要的:
var Activity = function(argsObj){
this.activityType = argsObj.activityType || "Default value";
};
Activity.prototype.doIt = function(){
console.log("I am " + this.activityType);
};
var Run = function(argsObj){
//re use Activity initializer
Activity.apply(this,arguments);
};
Run.prototype=Object.create(Activity.prototype);
Run.prototype.constructor = Run;
var Swim = function(argsObj){
//re use Activity initializer
Activity.apply(this,arguments);
};
Swim.prototype=Object.create(Activity.prototype);
Swim.prototype.constructor = Swim;
function activityFactory(argsObj){
return new window[argsObj.type](argsObj);
}
var r = activityFactory({type:"Run",activityType:"running"});
var s = activityFactory({type:"Swim",activityType:"swimming"});
r.doIt();//I am running
s.doIt();//I am swimming
console.log(r instanceof Run);//true
console.log(s instanceof Swim);//true
console.log(s instanceof Activity);//true
var wrong = activityFactory({type:"Run"});
wrong.doIt();//I am Default value
有關構造函數和原型的更多信息: https : //stackoverflow.com/a/16063711/1641941
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.