JavaScript函数内部的函数通过变量名称 [英] JavaScript call function inside a function by variable name
问题描述
pre $ var obj
$ = {}
obj.f = function(){
var inner = {
a:function(){
function b(){
alert ('得到它了!');
}
b(); // WORKS AS EXPECTED
x ='b';
[x](); //不工作,这个[x]()窗口[x]()等等
}
}
inner.a();
}
obj.f();
我尝试前缀 [x]()
具有不同的范围路径,但到目前为止没有成功。搜索现有的答案没有发现任何东西。如果 b()
直接放置在对象内部,则它与此[x]()
一起使用。由于<$ c中的变量范围,我想将 b()
作为函数a()
$ c> function a(),否则我需要将许多参数传递给 b()
。
////
重复的问题:Quentin在这个线程中提供了一个更优雅的答案imo。
使用匹配变量名称的字符串访问任意变量没有明确的方法。 (对于非常糟糕的方式,请参阅 eval
)。
[x]();
//不工作
尝试调用数组作为函数
无论
这个[x]()
该函数不是 inner
对象的属性。 p>
window [x]()
等等
由于它不是全局的,它不是窗口对象的属性。
如果您需要根据字符串变量的值调用函数,那么请在对象中组织函数并从中访问它们。
function b(){
alert('got it!');
}
var myFunctions = {
b:b
};
x ='b';
myFunctions [x]();
I'm having a difficulty calling a function inside of another function when its name is in a variable:
var obj = {}
obj.f = function() {
var inner = {
a: function() {
function b() {
alert('got it!');
}
b(); // WORKS AS EXPECTED
x = 'b';
[x](); // DOESN'T WORK, NEITHER this[x]() window[x](), etc.
}
}
inner.a();
}
obj.f();
I tried prefixing [x]()
with different scope paths but so far w/o success. Searching existing answers did not turn up anything. It works with this[x]()
if b()
is placed directly inside object inner. I would like to keep b()
as a function inside function a()
because of variable scope in function a()
, otherwise I would need to pass many parameters to b()
.
//// Re duplicate question: Quentin provided a more elegant answer in this thread imo.
There is no sensible way of accessing an arbitrary variable using a string matching the name of the variable. (For a very poor way to do so, see eval
).
[x]();
// DOESN'T WORK
You're trying to call an array as a function
NEITHER
this[x]()
The function isn't a property of the inner
object.
window[x]()
, etc.
Since it isn't a global, it isn't a property of the window object either.
If you need to call a function based on the value of a string variable, then organise your functions in an object and access them from that.
function b() {
alert('got it!');
}
var myFunctions = {
b: b
};
x = 'b';
myFunctions[x]();
这篇关于JavaScript函数内部的函数通过变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!