0

How would one call a method on a dynamically generated name? This is a case where I am passing the object name into a function and calling a method on that object. Something like this, where type is the name of the object I want to execute the method on:

function doSomething(type) {
    type.someMethod();
}

Note that I do not want to pass the object into the function.

3
  • if you don't want to pass the object. you can try using eval Commented May 29, 2018 at 13:26
  • try eval(type + ".method()"); Commented May 29, 2018 at 13:27
  • 2
    Depends on the scope of the object. If it's global window[type].someMethod () will work, but using a passed in object name is typically a terrible idea because it's prone to error. It would be best to pass in an actual object. Commented May 29, 2018 at 13:28

4 Answers 4

1

First, it is not clear what object that "type" belongs to. I'm guessing this is in scope, maybe something like this:

var typeObjects = {
    type1: {
      doSomething: function(){..},
      ..
    },
    type2: {
      doSomething: function(){..},
      ..
    },
    ..
}

Then, your function becomes the following:

function doSomething(typeName) {
    typeObjects[typeName].someMethod();
}

And then you would call it like so:

doSomething('type1');
Sign up to request clarification or add additional context in comments.

Comments

1

If your object is global, you could do this :

var global = global || window;

function doSomething(type) {
    global[type].someMethod();
}

var myObject = {
  someMethod : function () { console.log("calling someMethod") }, 
};
  
  
doSomething("myObject");

Comments

0

If you want to pass a variable name to a function, consider instead passing a property name of a predetermined object, so that your function is not unsafely accessing arbitrary objects from its scope with eval(), which is a bad practice for both security and performance reasons.

var myObject = {
  foo: { someMethod () { console.log('fooObj') } },
  bar: { someMethod () { console.log('barObj') } }
}

function doSomething (property) {
  if (myObject.hasOwnProperty(property)) {
    myObject[property].someMethod()
  }
}

doSomething('foo')
doSomething('bar')
doSomething('nil') // does nothing

Comments

0

You need to eval the object name or method.

eval(type)['someMethod']();

or

eval(type + '.someMethod()');

Also if your object is at window scope, you can do

window[type].someMethod();

1 Comment

Probably because you don't need to use eval to do this.

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.