Executing a dynamically named function in Javascript
Possible Duplicate:
How to execute a JavaScript function when I have its name as a string
Struggling with this one, and I can't seem to find a good resource on it.
Background: I'm creating a step system, and I'm passing the direcition/order within an attribute data-step="1"
. This controls the ID that will be shown (that parts easy), but also the function that needs to be called in order to grab the correct information.
The question is basically , how can I call a function who's name I need to build dynamically?
IE: step1(); step2();
step1(); step2();
Except I want to dynamically ADD that number in there.
// In an essense, what I'm trying to achieve:
// It's always called step and then followed by a number
[step + directionNumber](); // which isn't working
Also trying to avoid using eval
since we all know it's evil :)
Use
window["step" + directionNumber]();
When you write in the global scope
function someName(){
}
you're defining a property of the global object ( window
) with name someName
and value the function.
It's equivalent to
window.someName = function(){
}
So you can call your function as window.someName();
or, more useful here, as window['someName']();
A better solution would probably be to define an array of functions :
var stepFunctions = [];
stepFunctions[0] = function(){};
then you can call them using stepFunctions[directionNumber]();
将你的函数存储在一个对象中,以便按名称动态访问它们。
var funcs = {};
funcs.step1 = function(){ console.log("foo"); };
funcs.step2 = function(){ console.log("bar"); };
var text = "step",
number = 1;
funcs[text + number](); // foo
++number;
funcs[text + number](); // bar
链接地址: http://www.djcxy.com/p/94836.html
上一篇: 如何获得变量值的'typeof'