user2648914
user2648914

Reputation: 21

Calling prototype methods from within callback

I am creating a wrapper, mock sample as follows

var car = function() { 
}

car.prototype.method1 =  function() {
    this.method2();
}

car.protoptype.method2 = function(callback) {
   var request =  foo() //call to async method

   request.onsucces  = function() {
       this.method3();
   });
}

car.protoptype.method3 = function(callback) {
    this.method4(); //not found
}

car.protoptype.method4 = function(callback) {
     //code
}

//caller

var vehicle = new Car;
vehicle.method1()

My issue is that method 4 isn't called. As its nested in the onsuccess callback, would the 'this' not scope to the object in method 4?

Upvotes: 0

Views: 53

Answers (3)

Mulan
Mulan

Reputation: 135227

I think you will want fn.bind

request.onsuccess = this.method3.bind(this);

This way you can avoid any var that = this; context hacks

Note this relies on ECMAScript 5 and will not work in dinosaur browsers. If you need to support prehistoric software, look into es5-shim

Upvotes: 2

Brian Genisio
Brian Genisio

Reputation: 48137

This is probably due to the context from within the callback. You can store a reference to this as self:

car.protoptype.method2 = function(callback) {
   var self = this;
   var request =  foo() //call to async method

   request.onsucces(function() {
       self.method3()
   });
}

Others have suggested that you use Function.prototype.bind. The problem with this approach is that it doesn't work in old browsers (<= IE8). You can always polyfill this behavior if you prefer it.

Upvotes: 1

user2736012
user2736012

Reputation: 3543

Use Function.prototype.bind()

request.onsuccess = this.method3.bind(this);

This creates a new function with the value you passed as the first argument bound as the this value.

Upvotes: 1

Related Questions