1

My function gets model name as string, I need to create new instance of object based on its name.

ex.:

    modelName = 'MockA';
    model = new modelName();

this is ofcourse not working. in php i would use

    model = new $$modelName

thanks in advance

1

2 Answers 2

4

If MockA is in global scope you can use:

var model = new window[modelName]();

if not then you should reconsider the way you store your models, eg. with an object of models:

var my_models = {
   MockA: function() {},
   MockB: function() {}
}

and to access

var MockA = my_models.MockA;
// or
var model_name = 'MockA';
var MockA = my_models[model_name];
Sign up to request clarification or add additional context in comments.

4 Comments

but what if its not in global scope?
@irvgk If it's not attached on any object, then you are screwed.
anctualy is an mongoose model exported as odule.exports = mongoose.model('Client', new Schema({
For a more compatible solution in global scope, instead of window, consider var global = this; var model = new global[modelName](). But the object solution is far better.
0

You can use an object factory or bracket notation.

Sample of code:

// First example: Use a Factory
var MockA = function() {
    this.sayHello = function() {
      console.log('Hi from MockA ');
    };
  },
  MockB = function() {
    this.sayHello = function() {
      console.log('Hi from MockB ');
    }
  },
  factory = function(type) {
    var obj;
    switch (type) {
      case 'MockA':
        obj = new MockA();
        break;
      case 'MockB':
        obj = new MockB();
        break;
    }
    return obj;
  }

var objA = factory('MockA');
objA.sayHello();
var objB = factory('MockB');
objB.sayHello();

// Second example: Using bracket notation
var models = {
  BaseMockA: {
    sayHello: function() {
      console.log('Hi from BaseMockA ');
    }
  },
  BaseMockB: {
    sayHello: function() {
      console.log('Hi from BaseMockB ');
    }
  }
};
var baseObjA = Object.create(models['BaseMockA']);
baseObjA.sayHello();
var baseObjB = Object.create(models['BaseMockB']);
baseObjB.sayHello();

2 Comments

You are aware that both MockA and MockB will be created each time Factory is called, this is hugely ineffective.
@andrc, thanks for your comment. Please look at my edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.