这是为了我的目的而结束的正确方式吗

Was this the right way to make a closure for my purpose?

本文关键字:结束 方式吗 我的      更新时间:2023-09-26

我越来越慢慢地理解闭包,下面的代码也能工作。我想知道是否有一种更简单/更好的方法来完成我在这里要做的事情。

在下面的代码中,this只是指一个对象,该对象具有作为数组的sections属性。我在这个数组上循环,并绑定到每个section的每个el属性(DOM元素)的悬停事件。我为hover()方法提供的回调是闭包的来源。主this对象有两个方法.sectionMouseenter().sectionMouseleave(),它们的调用取决于事件类型(在我的代码中由e.type表示)是mouseenter还是mouseleave。作为一个参数,当前部分被传递给这些方法。当然,for循环的迭代在JavaScript中没有变量范围,因此需要一个闭包来封装section变量的引用。

    for (var i = this.sections.length - 1; i >= 0; i--) {
        var section = that.sections[i];
        section.el.hover(
            (function(section){
                return function(e){
                    that['section' + e.type.capitalize()](section);
                }
            })(section)
        );
    };

这是写这个闭包的"正确"方式,还是有更好的方式?

不要动态构建函数,而是将其放在for循环之外。

var sections = this.sections;
function dummy(section) {
    return function(e) {
        that['section' + e.type.capitalize()](section);
    }
}
for (var i = sections.length - 1; i >= 0; i--) {
    section.el.hover( dummy(sections[i]) );
}