假设我有以下 jQuery 代码:
var FooBar = {
zizzle: function (callback) {
var x, y, z;
// … do stuff with x y and z
callback(z, y, z);
}
}
$("a[href]").each(function () {
var link = this;
// do things with the link, e.g.
$(link).data('fiddle', "deedee")
function do_something() {
console.log("I would use the link variable here:", link)
// lots of code here using link
// blah, blah, blah link
}
$(this).click(function () {
FooBar.zizzle(do_something);
});
});
目前,因为do_something
在定义的函数内部,link
它可以访问该变量(闭包)。但是,我想知道是否可以避免为每个链接创建函数。我宁愿做一些更接近这一点的事情:
var FooBar = {
zizzle: function (callback) {
var x, y, z;
// … do stuff with x y and z
callback(z, y, z);
}
}
function do_something() {
console.log("I would use the link variable here:", link)
// lots of code here using link
// blah, blah, blah link
}
$("a[href]").each(function () {
var link = this;
// do things with the link, e.g.
$(link).data('fiddle', "deedee")
$(this).click(function () {
FooBar.zizzle(do_something);
});
});
所以do_something
它只创建一次。但是,如果我这样做,则do_something
不再具有link
.
假设在这种情况下无法更改代码,FooBar
并且它只需要一个回调并且不能发送任何其他参数。
我想到的唯一选择是这样的,至少只根据需要创建函数:
var FooBar = {
zizzle: function (callback) {
var x, y, z;
// … do stuff with x y and z
callback(z, y, z);
}
}
function do_something_maker(link) {
return function (x, y, z) {
console.log("I would use the link variable here:", link)
// lots of code here using link
// blah, blah, blah link
}
}
$("a[href]").each(function () {
var link = this;
// do things with the link, e.g.
$(link).data('fiddle', "deedee")
$(this).click(function () {
FooBar.zizzle(do_something_maker(link));
});
});
那是最好的选择吗?