简体   繁体   English

Javascript继承和基类原型的问题

[英]Issues with Javascript inheritance & base class prototype

I'm facing issues with configuring object while inheriting So I've 我在继承时遇到配置对象的问题,所以我已经

baseclass.prototype.activity =function(){ console.log("Im"+activity); }

and multiple other objects inheriting the base class(say A and B). 以及其他继承基类的其他对象(例如A和B)。

I want to configure run based on type of A and B So if it is A then calling run should make activity as Running and similarly with B it can be swimming I'm using following factory method for creating A and B depending on their type 我想根据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); 

};

Im not sure exactly what your goal is but if they are both inheriting from baseClass and the only difference is what activity displays then something like this would be sufficient: 我不确定您的目标是什么,但是如果它们都从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"

Not sure if this is what you're after: 不确定这是否是您要的:

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

More on constructor functions and prototype: https://stackoverflow.com/a/16063711/1641941 有关构造函数和原型的更多信息: https : //stackoverflow.com/a/16063711/1641941

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM