Xiaobai's growth path_What I learned today (2018.4.16)

The problem that has been bothering me for a long time

When using the for loop to bind the event execution, the last parameter of the loop is always obtained. The code is as follows

var param = {
    "0":{
        "id":"swipe-top",
        "scope":"0",
        "type":"Swiper",
        "content":[]
    },
    "1":{
        "id":"act-body",
        "scope":"1",
        "type":"Normal",
        "content":[]
    },

}

for(var scope in param){

    $("#"+param[scope].id).click(funciton(){

        show(param[scope]);

    });

}

function show(parm){

    console.log(parm);

}

The above code executes the bound click event, no matter if the id="swipe-top" or id="act-body" element is clicked, the parameter parm obtained in the executed function show is the last parameter whose scope is 1

After thinking about it for a long time, I hit the breakpoint and changed the parameters and tried it several times. I didn’t expect the problem. Later, Baidu searched and found that it was the reason for the JS closure

I only knew the word closure before, and I always thought it was a very important knowledge point, but I have only seen it in books, and I don’t know its concept and principle, and I didn’t involve it in my work.

Now that I have encountered it, I have a substantive understanding of closures.

At present, I understand that the closure is like the for loop binding event in the above code

My understanding is (not necessarily correct), the function function in the click event click is not executed when it is bound, and the show function in the function does not get the actual parameters at this time, so when the loop ends, when the click event is triggered, the function Execute, the parameter obtained by the show function is always the last value param[1] obtained by the for loop

The final solution to the above problems is as follows

for(var scope in param){

    $("#"+param[scope].id).click(

        (function(parm){

     return function(){
                show(parm);
     }

        })(param[scope])

    );

}

click binds an immediately executed function, using the value of the current loop param[scope] as a parameter, the content of the function is to return another function, this returned function is the final execution function of the click event, and the parameters obtained by show at this time parm is the value param[i] of the current loop. The function wrapped in this way is a closure. If there is something wrong, please point out.

Emmmmmm.....In fact, I wrote a lot of it before, but it disappeared for no reason after it was released, and only half of the draft was left. CSDN is really pitted!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325514549&siteId=291194637