0

I have this code:

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);

I want when getName is executed, the this variable points to a object.

The problem is that when the cb is executed, the this is not of the a instance.

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
Will
  • 1,616
  • 2
  • 13
  • 21

1 Answers1

1

You'll have to bind the scope of this to a:

b.callApi(a.getName.bind(a));
Sean
  • 1,239
  • 9
  • 16
  • That's it. I thought I tried it but I must have fumbled around enough to miss it. I'll mark this as the answer. Thanks. – Will May 06 '18 at 21:45