I have these 2 objects:
var Foo = function () {
this.name = 'foo';
};
Foo.prototype.sayName = function () {
console.log(this.name);
};
var Bar = function () {
this.cb = null;
};
Bar.prototype.setCb = function (cb) {
this.cb = cb;
};
Bar.prototype.callCb = function () {
this.cb();
};
And I have this result:
var foo = new Foo();
var bar = new Bar();
foo.sayName(); // "foo"
bar.setCb(foo.sayName);
bar.callCb(); // undefined
This happens because when we call foo.sayName
inside Bar
, this
is pointing to the Bar
object. Can someone explain what's happening here?
I also noticed that I can circumvent this by instead passing in an anonymous function bar.setCb(function() {foo.sayName();});
. Are there other/better ways around this problem?