Reputation:
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
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
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
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