Nested function parameters and 'this' context in Javascript
I'm trying to create a chain of functio开发者_开发技巧n 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.
At the start of your Thing
function, put var that = this;
. You can then access the Thing
this
using that
.
精彩评论