【发布时间】:2011-06-28 15:27:15
【问题描述】:
我正在开发这个小型 javascript 库,并遵循各种建议,出于各种原因(变量封装、代码隐藏等),我将我的功能包装在一个闭包中。因为我查询 JSON 网络服务并显示结果,所以我还使用 jquery tmpl 引擎。
我想我理解闭包有什么好处,但我肯定不理解它们。这意味着我在所有这些范围变化和诸如此类的事情之间完全迷失了。特别烦人的是我得到的这个例外。考虑以下代码(相关代码的简化丑陋版本,但它重现了问题)
// something would be the object that handles all the library functionality
var something = function(){
// creating a local function that goes as a parameter into the Array.filter
function isBar(data){
return data.name === "bar";
}
// the template code
var bla = "<h1>${name}<\h1><h2>${attribute.filter(isBar)[0].value}</h2>";
// precompiling the the template
$.template("test", bla);
// and returning a function that should render the template with the provided data
return {
funny: function(){
$.tmpl("test", [{"name":"Fo", "attribute":[{"name":"bar", "value":"how"}]},
{"name":"Foo", "attribute":[{"name":"fnord","value":"can"}]},
{"name":"Fooo", "attribute":[{"name":"bar","value":"this"}]},
{"name":"Foooo", "attribute":[{"name":"Bar", "value":"be"}]}
]);
}
}
}();
// calling the function
something.funny();
因此,当调用 something.funny() 时,我希望会发生以下情况:作为闭包的函数 funny 在其原始上下文中被调用(例如,函数 isBar 和变量 bar 已定义)。所以当我打电话给$.tmpl 时,我希望模板中的attribute.filter(isBar) 也在这个范围内。但事实并非如此。我 Chrome 我得到ReferenceError: isBar is not defined。
如果有人愿意向我展示我的错误方式,我会非常高兴。
【问题讨论】:
标签: javascript closures jquery-templates