使用Underscore.js在嵌套函数中绑定它

时间:2014-03-27 10:32:39

标签: javascript underscore.js

我对Underscore.js中的 Bind 功能有疑问 假设我们有以下对象" room":

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');
});

在我的评论中指出的那一行,"这个"被绑在窗户上。这是预期的行为。

假设我们想绑定它到"房间"宾语。是否可以使用Underscore.js'绑定方法。

注意:我知道我可以用好的旧的"那=这个"常规。但我对此并不感兴趣。

2 个答案:

答案 0 :(得分:3)

是的,你绝对可以使用Underscore的bind

来做到这一点

你可以这样使用bind:

<强> CODE:

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

请注意this作为bind的第二个参数传递,这使this引用您想要的而不是window

<强> JSFIDDLE

您也可以使用call在没有Underscore绑定的情况下执行此操作。

<强> CODE:

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

<强> JSFIDDLE

答案 1 :(得分: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)

        });