tags:

views:

26

answers:

1

Hi,

I'm trying to create a chain of function calls using two objects.

I've added comments in the code to describe what I'm trying to do:

function Huh(parentContext) {
this.parentContext = parentContext;
this.check = function() {
    console.log(parentContext);
}
this.DoWork = function(successFunc) {
    console.log('Huh.DoWork');
    successFunc('yay');     
};}

function Thing() {  
this.nextSuccess = function(e) {    
    console.log('nextSuccess ' + e);
};

this.success = function(e) {
    console.log('success!! ' + e);

    var h = new Huh(this);  // It looks like 'this' doesn't mean the Thing context any more. ?!?!
    //h.check();    
    h.DoWork(this.nextSuccess);  // THIS BREAKS. 
};

this.fail = function() {
    console.log('fail');
};

this.firstBit = function(successFunc, failFunc) {
    var h = new Huh(this);  
    //h.check();        
    h.DoWork(this.success);     
};

// start with this function
this.Go = function() {
    this.firstBit(this.success, this.fail);
};}

It all breaks when I try to create a second instance of Huh in Thing.success.

I try to pass in this.nextSuccess however it seems like the 'this' context isn't the same anymore.

Please help.

+3  A: 

At the start of your Thing function, put var that = this;. You can then access the Thing this using that.

Skilldrick
Thanks for that. I don't suppose you could explain why it fails in the original code please? I'd love to get a better understanding :)
sf
Yes, I could! In a nested function the inner function has access to all the outer functions variables (this is called closure), but it has its own `this` variable. So the `this` in `Thing` is a different `this` to the `this` in `function(e) {}`. When you assign `this` to `that`, you're basically 'saving' the `Thing` `this` variable for later use.
Skilldrick
awesome :D thanks heaps for your help
sf