Reputation: 23577
I have a service that runs in the background and synchronizes data. I register a controller as a callback and when the update happens I would like to fire off a callback. All of this works great, however, now inside that callback I want to call another function in the service....
Controller.prototype.update = function(){
this.service.test();
};
This fails saying that service is undefined but I can not figure out why. My understanding is that prototype allows for inheritance (which is a weak spot in my JS skills), which I will want if I want child objects to inherit some functionality while allowing me to override some other functionality (in this case update). I would like this option so I would like to keep the function on the prototype. So I would like to avoid something like this, even though it works.
Upvotes: 1
Views: 86
Reputation: 44916
The issue is that the this
keyword in JavaScript can change depending on the execution context. It's dependent on where it is invoked from, not where it is defined.
You are losing the context because of how it is called. If you want to ensure the context is maintained, you can you the bind()
function to fix the context to something of your choosing:
// Creates a new function that is permanantly bound
// to the current object that `this` is pointing to
service.register(this.update.bind(this));
Here is an updated Plunkr showing the working code using the bind()
function.
If you can't use the bind()
function, or the Polyfill implementation in the MDN article listed above isn't feasible, then you can also use a closure to ensure the correct call is being made:
//Capture the current `this` using a closure
var _this = this;
service.register(function(){
_this.update();
});
Example Plunker: http://plnkr.co/edit/buv66fexxZr04x7EACvE?p=preview
Upvotes: 2