繁体   English   中英

我有一个JavaScript范围错误,我不知道如何解决此问题

[英]I have a javascript scope error, I don't know how to fix this

浏览器在'Task.prototype.start'中告诉我'this.clear'是未定义的...这是类(函数)及其原型:

function Task(_func, _ms, _repeats, _args)
{
    if (typeof _func != 'function') throw '_func is not `function`';
    if (typeof _ms != 'number') throw '_ms is not `number`';
    if (typeof _repeats != 'number') _repeats = 0; // default: no repeats, run once. optional
    // _args is optional
    this.func = _func;
    this.ms = _ms;
    this.repeats = _repeats;
    this.args = _args;
    this.tID = 0;
    this.runCounter = 0;
}

Task.prototype.isRunning = function()
{
    return (this.tID != 0);
};
Task.prototype.runsOnce = function(){
    return (this.repeats == 0);
};
Task.prototype.clear = function()
{
    if (this.isRunning())
    {
        if (this.runsOnce())
        {
            clearTimeout(this.tID);
        }
        else
        {
            clearInterval(this.tID);
        }
    }
    this.tID = 0;
    this.runCounter = 0;
};
Task.prototype.start = function()
{
    this.clear();
    var _this = this;
    var _exec = function()
    {
        if (_this.runsOnce())
        {
            _this.func(_this.args);
            _this.clear();
        }
        else
        {
            if (_this.runCounter > 0)
            {
                _this.runCounter--;
                _this.func(_this.args);
            }
            else if (_this.runCounter == -1)
            {
                _this.func(_this.args);
            }
            else
            {
                _this.clear();
            }
        }
    };
    if (this.runsOnce())
    {
        this.runCounter = 0;
        this.tID = setTimeout(_exec, this.ms);
    }
    else
    {
        this.runCounter = this.repeats;
        this.tID = setInterval(_exec, this.ms);
    }
}

编辑:我如何使用它...

Task.tasks = {};
Task.exists = function(_ID)
{
    return (_ID in Task.tasks);
}
Task.create = function(_func, _ms, _repeats, _args, _ID)
{
    if (Task.exists(_ID)) return;
    Task.tasks[_ID] = new Task(_func, _ms, _repeats, _args);
}
Task.start = function(_ID)
{
    if (!Task.exists(_ID)) return;
    Task.tasks[_ID].start();
}
Task.clear = function(_ID)
{
    if (!Task.exists(_ID)) return;
    Task.tasks[_ID].clear();
}


//test task
__task = new Task(function(a){console.log( (new Date()).getTime()+': '+a ) }, 2000, 0, '[args]');

如果在.start()方法中遇到该错误,那是因为this值不是应该的值。 并且,该问题可能是由于调用.start()方法的方式而发生的。 由于您没有向我们展示如何调用.start()方法,因此我们无法具体解决那里的问题。 但是,您需要确保以obj.start()的形式调用它,其中objTask对象。

在这方面的一个常见错误是将obj.start作为回调传递,而没有意识到无论调用该回调的人都不会将其称为obj.start()

请包括您如何致电.start()以便我们更具体地提供帮助。

您的代码很好。 确保您使用了new

var task = new Task(...);
task.start();

可能您正在做:

var task = Task(...);

不会创建适当的this值,从而导致错误。

干杯

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM