[英]Nested function parameters and 'this' context in Javascript
我正在尝试使用两个对象创建函数调用链。
我在代码中添加了注释,以描述我要执行的操作:
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);
};}
当我尝试在Thing.success中创建Huh的第二个实例时,一切都中断了。
我尝试传递this.nextSuccess,但是似乎“ this”上下文不再相同。
请帮忙。
在Thing
函数的开头,输入var that = this;
。 然后,您可以使用that
访问Thing
this
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.