JavaScript关闭 - 评估()和捕获变量在Eval()的范围
我的问题是关于JavaScript闭包和Eval()函数。JavaScript关闭 - 评估()和捕获变量在Eval()的范围
我有一些看起来像这样的代码,还有一些其他jQuery插件相关代码taht没有显示。如果需要,我可以用更多的代码更新问题。
var _CurrentDataRowIndex = 1;
function LoadParsedRowTemplate(rowData, type) {
var result;
var asyncbinder = /&\{[\S\s]*?}&/g;
while ((result = asyncbinder.exec(template)) != null) {
replacement = eval("$.fn.ScreenSetup." + result[0].substring(2, result[0].length - 3) + ", rowData, " + _CurrentDataRowIndex + ")");
template = template.replace(result[0], "AsyncBind!!");
asyncbinder.lastIndex = 0;
}
}
function AsynchronousBind(asyncFunc, args, rowData, rowIndex) {
var watchTimer;
asyncFunc.apply(this, Array.prototype.slice.call(args.FunctionArgs, 0));
watchTimer = setInterval(function() {
if (args.finished) {
clearTimeout(watchTimer);
}
else {
try {
console.log("watching the async function for a return on row: " + rowIndex);
}
catch (err) {
}
}
}, 1000);
}
评估和演示没有捕捉rowData和_CurrentDataRowIndex,当AsynchronousBind函数被调用这两个是不确定的。 eval如何处理闭包?我想知道为什么在AsynchronousBind中未定义rowData和rowIndex参数。
编辑:
我知道的eval(争议性),但是这是一个防火墙应用程序后面,我加入到使用eval我们已经写了一个插件解析包含HTML和JavaScript的模板。
这里是字符串的示例被传递到的eval():
"$.fn.ScreenSetup.AsyncBind(_CurrentDataRow.isPromotionAvailable, {
'FunctionArgs': {'doAsync' : true,
'finished' : false},
'Property': 'isPromotionAvailable()',
'ControlType': 'TextBox',
'ControlIdPrefix': 'promoAvail'}, rowData, 3)"
编辑(固定):
意识到,当我加入rowData和rowItem II忘记改变以下在我的插件:
var asyncMethods = {
AsyncBind: function (func, args) { return AsynchronousBind(func, args) }
}
应在被:
var asyncMethods = {
AsyncBind: function (func, args, rowData, rowIndex) { return AsynchronousBind(func, args, rowData, rowIndex) }
}
更新此修复了AsyncBind函数中未定义的引用。
Understanding eval scope是一篇有趣的文章。它表明范围在浏览器中不一致。如果您必须使用eval,那么您应该小心只指望它在全局范围内,并且不要在本地范围内重用全局变量名称,以免在本地进行评估。
更好的是,不要使用eval。你可能有其他选择。
感谢您的文章链接 – dmck
如果问题包含“'eval'”,那么答案是:**不要**。 – Quentin
看起来你正在尝试使用'eval',因为你只知道如何使用点符号来访问属性。请改为了解[方括号表示法](http://www.dev-archive.net/articles/js-dot-notation/)。 – Quentin
提示:请勿使用eval。它不需要你想做的事情。此外,您传递的代码无效:没有起始括号。 –