我有这个代码:
function A() {
this.name = 'John';
}
A.prototype.getName = function() {
return this.name;
}
function B() {
}
B.prototype.callApi = function(cb) {
var context = arguments[0];
setTimeout(function() {
console.log('server data combine with ' + cb());
}, 1000);
}
var a = new A();
console.log(a.getName());
var b = new B();
b.callApi(a.getName);
我希望当执行 getName 时,this
变量指向a
对象。
问题是当 cb
执行后,this
不属于a instance
.
最佳答案
您必须将 this
的范围绑定(bind)到 a
:
b.callApi(a.getName.bind(a));
关于javascript - 使用其上下文调用原始回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50204773/