I'm just overworking my JS code and wish to replace my eval()
's with window[functionName]
. So I just made a quick test in the JSFiddle and all works well with the following lines:
我只是过度使用我的JS代码,并希望用window [functionName]替换我的eval()。所以我刚刚在JSFiddle中进行了快速测试,并且所有方法都适用于以下几行:
var fnName = "Page_test";
var foo = "yammy";
var Page_test = function(bar) {
return bar;
}
var Obj = window[fnName];
alert(Obj(foo));
(Link to this JSFiddle -> http://jsfiddle.net/juSHj/)
(链接到这个JSFiddle - > http://jsfiddle.net/juSHj/)
Now I try to replace the following lines of code with the evil eval()
with the above concept:
现在我尝试使用上述概念将邪恶的eval()替换为以下代码行:
old code: (works like a charm / fired after ajax success)
旧代码:(工作就像魅力/ ajax成功后解雇)
...
success: function(ret) {
if(returnFnAjaxForm != "") {
eval(returnFnAjaxForm+"('"+encodeURI(jQuery.trim(ret))+"')");
}
}
...
new code:
Returns: Uncaught TypeError: Property 'dummyFn' of object [object Window] is not a function
返回:未捕获的TypeError:对象[对象窗口]的属性'dummyFn'不是函数
...
success: function(ret) {
if(returnFnAjaxForm != "") {
fnObj = window[returnFnAjaxForm];
if(typeof(fnObj) == "function") { // this is optional
fnObj(encodeURI(jQuery.trim(ret)));
}
}
}
...
I'm curious where I made my mistake. Yes the function I try to fire exists and is defined with var
. Is this concept may not possible to use it on an ajax-response?
我很好奇我犯了哪些错误。是的,我尝试触发的功能存在,并使用var定义。这个概念可能无法在ajax响应中使用它吗?
Thanks for any help.
谢谢你的帮助。
(Using jQuery)
1 个解决方案
#1
10
If you declare your function in a closure, it's not a member of window. Example :
如果在闭包中声明函数,则它不是窗口的成员。示例:
var in_window = '132';
alert(window['in_window']); // Alert 132
(function() {
var not_in_window = '132';
alert(window['not_in_window']); // Alert undefined
})();
So be careful of where you declare your Page_test
variable. If you really want to put in window, you can do window.Page_test = Page_test
.
因此,请注意声明Page_test变量的位置。如果你真的想放入窗口,你可以做window.Page_test = Page_test。
The best you can do is to use an object for all your possible callbacks. Like this :
您可以做的最好的事情是使用一个对象来进行所有可能的回调。喜欢这个 :
var callbacks = {
foo : function() {},
foo1 : function() {},
foo2 : function() {},
foo3 : function() {}
};
var obj = callbacks[fnName];
#1
10
If you declare your function in a closure, it's not a member of window. Example :
如果在闭包中声明函数,则它不是窗口的成员。示例:
var in_window = '132';
alert(window['in_window']); // Alert 132
(function() {
var not_in_window = '132';
alert(window['not_in_window']); // Alert undefined
})();
So be careful of where you declare your Page_test
variable. If you really want to put in window, you can do window.Page_test = Page_test
.
因此,请注意声明Page_test变量的位置。如果你真的想放入窗口,你可以做window.Page_test = Page_test。
The best you can do is to use an object for all your possible callbacks. Like this :
您可以做的最好的事情是使用一个对象来进行所有可能的回调。喜欢这个 :
var callbacks = {
foo : function() {},
foo1 : function() {},
foo2 : function() {},
foo3 : function() {}
};
var obj = callbacks[fnName];