0

我的問題:命名功能和匿名函數具有不同的效果

我重構一些我的代碼,並在一定長的匿名功能,給予名稱。不幸的是,它以我不明白的方式打破了應用程序。

代碼

匿名版本工作正常,

警報(distributeurs.length);

不同於0

var group = this.settings.group, //group used to store all the markers added to the map 
      leads = this.model.get("leads"), // collection of leads 
      distributeurs = new Distributeurs(), // collection of distributeurs 
      map = this.settings.map, 
      addLeadsCollection = this.addLeadsCollectionFnContructor(); 


     //ajax calls to populate collection 
     $.when(leads.fetch({ data: $.param({ departementCode: departementCode }) }), distributeurs.fetch({ data: $.param({ departementCode: departementCode }) })).done(
      function() //the function 
      { 
       alert(distributeurs.length); //the alert 
       distributeurs.map(function (distributeur) 
       { 
        addLeadsCollection(leads.filter(function (lead) 
        { 
         return distributeur.get("id") === lead.get("distribution"); 
        } 
       )); 
       } 
      ); 
      } 
     ); 

命名的版本:它什麼都不如

警報(distributeurs.length);

總是價值爲0。

var group = this.settings.group, //group used to store all the markers added to the map 
      leads = this.model.get("leads"), // collection of leads 
      distributeurs = new Distributeurs(), // collection of distributeurs 
      map = this.settings.map, 
      addLeadsCollection = this.addLeadsCollectionFnContructor(); 



     //the function 
     var addCollections = function() { 
      alert(distributeurs.length); //the alert 
      distributeurs.map(function(distributeur) { 
       addLeadsCollection(leads.filter(function(lead) { 
        return distributeur.get("id") === lead.get("distribution"); 
       } 
       )); 
      } 
      ); 
     }; 

     //ajax calls to populate collection 
     $.when(leads.fetch({ data: $.param({ departementCode: departementCode }) }), distributeurs.fetch({ data: $.param({ departementCode: departementCode }) })).done(
      addCollections() 
     ); 

我的問題

爲什麼這兩個功能不同的行爲,我應該如何申報我命名的功能,使之像匿名一。

回答

3

addCollections()中刪除括號。您正在立即調用該函數;你想要做的是傳遞函數。

其實你的功能在這兩種情況下都是匿名的。您在第二種情況下完成的所有操作都是將該函數的引用分配給一個變量。爲了使功能不是匿名,你可以使用一個函數聲明

function addCollections() { 
    // Stuff... 
} 

...或使用named function expression

var addCollections = function someName() { 
    // someName is now a reference to the function, but only 
    // within the function 
}; 
1

這不是一個命名的函數,你要分配功能一個名爲addCollections的變量。你的問題是,你調用的函數,而不是在參考路過這裏:

$.when(leads.fetch({ data: $.param({ departementCode: departementCode }) }), distributeurs.fetch({ data: $.param({ departementCode: departementCode }) })).done(
      addCollections() 
     ); 

刪除括號:

$.when(leads.fetch({ data: $.param({ departementCode: departementCode }) }), distributeurs.fetch({ data: $.param({ departementCode: departementCode }) })).done(
       addCollections 
      );