I'm trying to implement some basic object orientation in javascript like so:
function Cat(name) {
this.name = name;
}
Cat.prototype.sayName = function() {
console.log(this.name);
};
Cat.prototype.fetchCat = function() {
someAsyncCall()
.success(this.sayName)
.error(someOtherMethod);
};
when someAsyncCall
is finished sayName
gets called but the this
scope is not what I expect. I can solve it by binding:
Cat.prototype.fetchCat = function() {
someAsyncCall()
.success(this.sayName.bind(this))
.error(someOtherMethod.bind(this));
};
Is there some syntactically "nicer" solution to this than having to remember to .bind
all the time when in callbacks?