Was this the correct way to do closure for my purpose?

I slowly understand the whole closure and the following code works. I am wondering if there is an easier / better way to accomplish what I am trying to do here.

The code below this

simply refers to an object that has a property sections

that is an array. I loop over this array and bind to the hover event of each property el

(DOM element) of each section

. The I callback passed to the method hover()

is where the closure occurs. The main object this

has two methods .sectionMouseenter()

and .sectionMouseleave()

that are called depending on whether the event type (represented e.type

in my code) mouseenter

or mouseleave

. The current section is passed to these methods as an argument. Of course, loop iteration is for

not scoped in JavaScript, so closures are needed to encapsulate the variable reference 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)
        );
    };

      

Is this the "correct" way to write this closure, or is there a better way?

+3


source to share


1 answer


Don't build a function on the fly, but expose it outside of the for loop.



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]) );
}

      

+6


source







All Articles