Problemas con la herencia de Javascript y el prototipo de clase base

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).

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

activityFactoryObject.prototype.makeObj = Object.create(baseclass);
activityFactoryObject.prototype.createObject = function (config) {

    switch (config) {
    case "running":

        this.makeObj = A;
    case "swimming":

        this.makeObj = B;

    this.makeObj.prototype = baseclass.prototype;  
    return new this.makeObj(config); 


preguntado el 27 de noviembre de 13 a las 05:11

2 Respuestas

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.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"

respondido 27 nov., 13:05

Since it is a prototype , will both share a common instance ?? - Ecko123

a common instance of the function, but it doesn't look like you are storing the activity they are doing in your code, just printing it. If you want to store it that would require more changes, im not sure you need child objects for this though, just instances and you could easily have a separate intstance of the activity and still share the same activitiy method, i would use a getter and setter. I will make a jsfiddel to explain better - kkemple

No estoy seguro de si esto es lo que buscas:

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
Run.prototype.constructor = Run;

var Swim = function(argsObj){
  //re use Activity initializer
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:

contestado el 23 de mayo de 17 a las 12:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.