Understanding $.proxy() in jQuery

前端 未结 4 927
陌清茗
陌清茗 2020-11-29 14:39

From docs I understand that .proxy() would change the scope of the function passed as an argument. Could someone please explain me this better? Why should we do

4条回答
  •  情书的邮戳
    2020-11-29 15:11

    The same goal can be achieved using a "Immediately-Invoked Function Expression, short: IIFE" self executing function:

        $('#myElement').click(function() {  
          (function(el){
             setTimeout(function() {
                  // Problem! In this function "this" is not our element!
                el.addClass('colorme');
            }, 1000);
          })($(this)); // self executing function   
        });
    .colorme{
      color:red;
      font-size:20px;
    }
    
    
    
      
      
      JS Bin
    
    
    
    
      
    Click me

提交回复
热议问题