2014-03-27 34 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) 

     });