user429620
user429620

Reputation:

Call function from string inside object?

I have a function name in a string:

 var func = "doTest";

I need this function to be applied to the current instance ("this");

So I need it to call:

 this.doTest();

How can I do this? I cannot go via window.

Thanks, Wesley

Upvotes: 7

Views: 9436

Answers (4)

meder omuraliev
meder omuraliev

Reputation: 186562

Just use the construct of object[functionName]();, like so:

function Person() {};
Person.prototype.speak = function() { alert('ohai'); };
var john = new Person, action = 'speak';

john[action]();

Alternative style:

var Person = {  
  speak: function() { alert('ohai'); }, 
  speakDelegate: function() { var action = 'speak'; this[action](); } 
};
Person.speakDelegate();

Upvotes: 21

davin
davin

Reputation: 45525

this[func]();

No need to .call or .apply since context is held in the reference.

For example:

var obj = {
   doTest: function(){ console.log(this); },
   fn: function(){ var name='doTest'; this[name](); }
};
obj.fn(); // logs the object, proving this has the correct context.

Upvotes: 6

Porco
Porco

Reputation: 4203

If you are using jquery you can just do:

$(this)[func]()

Upvotes: 0

JaredPar
JaredPar

Reputation: 754665

Try the following

var funcObj = this["doTest"];
funcObj.apply(this);

What this does is grab the member named doTest from this. It then executes the function via apply and tells javascript to bind this as this within the function. I think the example is a bit less confusing if you consider the same code on a non-this value

var obj = {
  doTest: function() {
    console.log("doTest called");
  }
};

var doTestFunc = obj["doTest"];
doTestFunc.apply(obj);

In this case the method doTest will be executed with the value obj as this

Upvotes: 4

Related Questions