我无法弄清楚如何传递对象方法,而不是在进行回调时对“通用原型”方法进行排序。
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函数中的所有方法,但是我知道这不是实现它的方法所以现在我正在尝试使用原型。
我知道在Client()函数中有一些解决方案“绑定”onLogin函数,但我想了解这个问题。
答案 0 :(得分:4)
您需要使用apiCall
将bind
的上下文绑定到回调:
Client.prototype.apiCall = function(method, params, callback) {
var bound = callback.bind(this);
bound();
}
否则,onLogin
中的此项将设置为全局对象。
有关详细信息,请参阅Call, Apply And Bind。
基本上
.bind(obj)
会返回一个函数,该函数在调用时会在内部使用(obj)
作为this
。
所以你创建了这个绑定,然后你调用它。
答案 1 :(得分:3)
您可以使用call
或apply
绑定this
,请参阅代码段。我为了演示目的修改了您的代码。希望它能为你澄清事情
function Client() {
this.name = "hello";
}
Client.prototype = {
apiCall: function(method, params, callback) {
try {
var trial = method.call(this, params);
callback.apply(this, [null, trial]);
} catch (e) {
callback.apply(this, [e, null]);
}
},
onLogin: function(error, data) {
if (error) {
Helpers.report('<b style="color: red">' +
'An error occured!</b> <i>' +
error.message + '</i>')
} else {
Helpers.report(this.name, ' (data.result = ' + data.result + ')');
}
},
start: function() {
Helpers.useCSS(1);
// error from this.rtm.start
Helpers.report('Command: <code>', 'this.apiCall(this.rtm.start, {will: \'not work\'}, this.onLogin);','</code>');
this.apiCall(this.rtm.start, {will: 'not work'}, this.onLogin);
// this.rtm.works is ok
Helpers.report('<br>Command: <code>',
'this.apiCall(this.rtm.works, {will: \'work\'}, this.onLogin);',
'</code>');
this.apiCall(this.rtm.works, {
will: 'work'
}, this.onLogin);
},
// --------------------------------
// added rtm for snippet demo
rtm: {
start: function(params) {
return anerror;
},
works: function(params) {
return {
result: 'worked, <code>params: ' + JSON.stringify(params) + '</code>'
};
}
},
};
new Client().start(); //<= here
&#13;
<script src="https://rawgit.com/KooiInc/Helpers/master/Helpers.js"></script>
&#13;