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

标签 javascript this self

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/

相关文章:

javascript - 如何获得等级值

javascript - Jquery 在 .hover() 上显示和隐藏 div

javascript - 从返回的 promise 中设置成员变量

C# 如何将 'this' 关键字破解/修复到结构中?

Python: self 作为属性

ios - 我怎样才能得到真正的 'self' ,哪个节点运行 SKaction 序列

php - 检测 "overall average"图片颜色

javascript - javascript中的dispatchEvent所有元素

javascript - 使用 JavaScript 与 SVG 元素交互

函数参数列表中未定义 Python "self"