Javascript继承问题&基类原型

时间:2013-11-27 05:13:45

标签: javascript inheritance 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); 

};

2 个答案:

答案 0 :(得分:0)

我不确定你的目标究竟是什么,但是如果它们都是从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"

答案 1 :(得分:0)

不确定这是否是你所追求的:

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