gpt4 book ai didi

javascript - 使用 `this` 在函数内部调用函数的问题

转载 作者:行者123 更新时间:2023-11-29 16:07:10 24 4
gpt4 key购买 nike

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 返回 LexicalEnvironmentEnvironmentRecord[[ThisValue]] 属性>ExecutionContext 正在运行的函数(参见 the spec )。

其值取决于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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com