绑定

2017-06-13 26 views
-1

如何我可以使用绑定()在下面的代码,这样我不失去“这个”绑定

this.getContactName(id, (error, contactName) => { 
    if (error) return callback(error, null); 

    // want to access "this" here e.g., 
    // this.indexScore = 1 

    return callback(null, contactName); 
}); 
+0

'this.indexScore = 1' - where'indexScore'?你想绑定什么'this'的值? – Quentin

回答

0

范围尝试这样 让我知道,如果我错了这里

this.getContactName(id, (error, contactName) => { 
    if (error) return callback(error, null); 

    // want to access "this" here e.g., 
    // this.indexScore = 1 

    return callback(null, contactName); 
}).bind(this); 
1

您可以使用call()apply()这样的:

this.getContactName(id, (error, contactName) => { 
    if (error) return callback.call(this, error); 

    // want to access "this" here e.g., 
    // this.indexScore = 1 

    return callback.call(this, contactName); 
}); 

或用apply()

this.getContactName(id, (error, contactName) => { 
    if (error) return callback.apply(this, [ error ]); 

    // want to access "this" here e.g., 
    // this.indexScore = 1 

    return callback.apply(this, [ contactName ]); 
}); 

这两种方法结合的第一个参数作为this值。区别在于,apply()有一个函数参数数组作为第二个参数,而call()只有一个参数比初始函数调用多(第一个是函数的this值)。有关更多信息,请参阅此answer

+0

[删除评论 - 我没有注意] – shabs

0

直截了当的答案是包装的匿名函数在括号中并在其上调用bind(this)

this.getContactName(id, ((error, contactName) => { 

    if (error) return callback(error, null); 
    return callback(null, contactName); 

}).bind(this)); 

的更细致的回答是箭头的功能不绑定自己的this - 他们是“词法范围“ - 所以这实际上不是必须的。