2

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.

2
  • 2
    When you're using nested functions, please try to reflect this in the indentation. It makes it MUCH easier to read. Commented Jun 29, 2010 at 9:46
  • Sorry about that. I tried to get the indentation working but the code block just kept breaking. Commented Jun 29, 2010 at 9:57

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

1 Comment

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 :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.