我在进行回调时很难弄清楚如何传递对象方法而不是对“通用原型(prototype)”方法进行排序。
function Client() {
this.name = "hello";
}
Client.prototype.apiCall = function(method, params, callback) {
callback();
}
Client.prototype.onLogin = function(error, data) {
console.log(this.name);// undefined!!!!
}
Client.prototype.start = function() {
var self = this;
self.apiCall('rtm.start', {
}, self.onLogin) // passing of method like this does not work.
}
我通过了onLogin方法,但是它不起作用。这是我重新编写的代码。以前,我将所有方法都嵌套在Client函数中,但是,我了解到,这不是做到这一点的方法,所以现在我尝试使用原型(prototype)。
我知道在Client()函数内部有一些“绑定(bind)” onLogin函数的解决方案,但是我想理解这个问题。
最佳答案
您需要使用apiCall
将bind
的上下文绑定(bind)到回调:
Client.prototype.apiCall = function(method, params, callback) {
var bound = callback.bind(this);
bound();
}
否则,
onLogin
中的this设置为全局对象。有关更多详细信息,请参见Call, Apply And Bind。
关于javascript - 将回调函数与原型(prototype)函数一起使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27578557/