window.onerror = function(e){alert(e)};
function main(){
this.work = [];
this.start_working = function() {
try{
if(this.work.length > 0){
var y = this.work.shift();
y.func(y.args);
}
}
catch(e){alert(e)};
};
this.add_work = function(f, a){
this.work.push({func:f, args:a});
};
this.foo = function(){
function footoo(){alert("bar");}
this.add_work(footoo);
};
this.foothree = function(){
this.add_work(this.foo);
};
this.start = function(){
setInterval(function(){this.start_working();}.bind(this), 1);
};
};
x = new main();
x.start();
x.foothree();
这是我在别处使用的函数的简化版本,用于按顺序运行动画。
预期行为:
this.foothree
是在区间上加上foo处理的。然后处理 this.foo
,将 footoo
添加到最终处理的间隔中,发出“bar”警报。
问题:
当处理this.foothree
时,抛出一个错误:
TypeError: this.add_work is not a function.
为什么我不用更简单的东西:
基本上我需要一个函数,它允许我将由更简单的动画组成的更复杂的动画组合到要处理的队列中,以便我可以重用该动画。 Foothree
在此实例中只是模拟一个调用,该调用会将真正的动画 footoo
添加到要处理的队列中。 Footoo
将由更简单的动画 foo
组成,它们将按顺序执行。
最佳答案
this
返回
正在运行的函数(参见 the spec )。LexicalEnvironment
的 EnvironmentRecord
的 [[ThisValue]]
属性>ExecutionContext
其值取决于how the function is called .如果你打电话
this.foo = function(){
function footoo(){alert("bar");}
this.add_work(footoo);
};
在声明的函数中没有 add_work
方法。
您应该采用 var _self = this;
模式以指向正确的调用上下文。
基本上代码应该重写如下:
function main(){
var _self = this;
this.work = [];
this.start_working = function() {
try{
if(_self.work.length > 0){
var y = _self.work.shift();
y.func(y.args);
}
}
catch(e){alert(e)};
};
this.add_work = function(f, a){
_self.work.push({func:f, args:a});
};
this.foo = function(){
function footoo(){alert("bar");}
_self.add_work(footoo);
};
this.foothree = function(){
_self.add_work(_self.foo);
};
this.start = function(){
setInterval(function(){_self.start_working();}, 1);
};
};
编辑:
从原始代码中删除了 .bind(this)
。
关于javascript - 使用 `this` 在函数内部调用函数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38332106/