Javascript 按不属于全局作用域的名称调用函数
假设我有这样的东西:Javascript 按不属于全局作用域的名称调用函数,javascript,jquery,Javascript,Jquery,假设我有这样的东西: var MyApp = MyApp || {}; MyApp.feature = (function($){ var somelocalVariable, otherone init = function() { }, somePrivateFunction = function() { var functionName = 'otherFunction'; //how can I call otherFunction by
var MyApp = MyApp || {};
MyApp.feature = (function($){
var somelocalVariable,
otherone
init = function() {
},
somePrivateFunction = function() {
var functionName = 'otherFunction';
//how can I call otherFunction by name (using variable above)
},
otherFunction = function() {
};
return {
init: init
}
})(jQuery);
在本例中,如果执行window['otherFunction']
操作,则不会发生任何事情,因为它不是全局函数。如何将其作为更私有的作用域的一部分执行?将“窗口”替换为“此”
这根本没有道理
MyApp.feature
变为otherFunction
,{init:init}
被丢弃。无论如何,如果你想按名称引用函数,请将函数放在对象中。@minitech-我认为OP的目的是返回一个具有属性的对象,而不仅仅是otherFunction。你的函数声明也不匹配。不确定代码中发生了什么,因为这很奇怪,但你是否想过尝试这个[functionName]
???现在您有了一组隐式全局变量,而且window['otherFunction']
应该可以正常工作。(提示:使用函数声明样式,不要对每个var
进行多个声明。另外,启用严格模式。)
this[functionName]();