2014-03-27 71 views
3

綁定這一個嵌套函數我有一個關於在Underscore.js 的綁定特徵的問題,讓我們說我們有以下的對象「房間」:與Underscore.js

var person = 'Bob'; 

$(function() { 

    var room = { 
     capacity: 10, 
     exits: 2, 
     count: 0, 
     person: '', 
     addPerson: function (name) { 
      this.count += 1;    

      var nestedFunction = function (nameOfPerson) { 

       // this is bound to window 
       this.person = nameOfPerson; 

      }(name);   
     } 
    }; 

    room.addPerson('dave'); 
}); 

在在我的評論中指出的那一行,「this」是綁定在窗口上的。這是預期的行爲。

比方說,我們要綁定它的「房間」對象。用Underscore.js的bind方法可以做到嗎?

注:我知道我可以處理這與老「這=這個」例程。但我對此不感興趣。

回答

3

是的,您絕對可以使用Underscore的bind來做到這一點。

您可以用這種方式綁定:

CODE:

var nestedFunction = _.bind(function (nameOfPerson) { 
    this.person = nameOfPerson; 
},this); 

,但請注意this作爲第二個參數bind,這使得this指的是你想要什麼,並沒有通過的window

JSFIDDLE

您也可以通過使用call做到這一點,沒有下劃線的綁定。

CODE:

addPerson: function (name) { 
     this.count += 1;    
     var nestedFunction = function (nameOfPerson) { 
      this.person = nameOfPerson; 
     };   
     nestedFunction.call(this,'dave'); 
    } 

JSFIDDLE

+2

+1但是,'nestedFunction.call'將不起作用,因爲IIFE的結果分配給它,而不是函數本身。 – thefourtheye

+0

謝謝@thefourtheye。其實,我已經更新了代碼片段,它不再是'IIFE'。該代碼位於下面的JSFIDDLE鏈接中。 –

+0

但OP的代碼只有IIFE – thefourtheye

0

我知道這可能不是幫助的問題,但我的問候骨幹無意中發現了這個問題。

我試圖保存一個模型,然後在回調中另一個模型。他是工作的最終結果。但是_.bind可以用在你不能訪問的任何其他函數中。

this.information.set('name', 'Bob'); 
    this.information.save(null, 
     { 
      success: _.bind(function(model, response) 
      { 
        console.log('Saved Information'); 
        this.review.set('review', "This is a test Review"); 
        this.review.save(null, 
        { 
          success: function(model, response) 
          { 
           console.log('Saved Review'); 
           location.reload(); 
          } 
        }); 
      }, this) 

     });