我对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'绑定方法。
注意:我知道我可以用好的旧的"那=这个"常规。但我对此并不感兴趣。
答案 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)
});