这可能有点抽象,但我正在尝试了解 JavaScript 闭包等。请使用以下代码:
function MyObj() {
var me = this;
this.foo = function(bar) {
// Do something with 'bar'
}
// Set up lots of local variables etc.
// ....
$(window).load(function() {
// Add a delegated click handler to specific <input> elements
$(document).on('click.myobj', 'input.special', function() {
// Do something with the <input> that triggered the click event
me.foo(this);
});
});
}
var myObj = new MyObj();
传递给绑定(bind)到单击事件的匿名函数创建一个引用me
的闭包。我想知道的是是否最好做这样的事情(以避免关闭):
$(window).load(function() {
// Add a delegated click handler to specific <input> elements
(function(localMe) {
$(document).on('click.myobj', 'input.special', function() {
// Do something with the <input> that triggered the click event
localMe.foo(this);
});
})(me);
});
这是一个更好的方法,还是我对创建一个闭包过于偏执?或者,还有“第三条路”吗?
<小时/>编辑
此外,这样做会更好吗:
$(window).load(function() {
// Add a delegated click handler to specific <input> elements
$(document).on('click.myobj', 'input.special', {localMe : me}, function(event) {
// Do something with the <input> that triggered the click event
event.data.localMe.foo(this);
});
});
最佳答案
后者(据我所知)效率更高,但可能无法衡量,除非在紧密循环中使用。
原因是所有变量解除引用都必须遵循作用域链。在后一种情况下,变量 localMe
可以在匿名函数的参数列表中找到。
在前一种情况下,变量不是在那里找到的,而是在外部作用域中找到的。这种沿着作用域链的遍历需要额外的时间。
关于javascript - 我应该避免创建这个 JavaScript 闭包吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13722581/