JavaScript 单例类型错误 : why does strict mode flag this?

标签 javascript jquery typeerror

我是 JavaScript 的新手,无法理解为什么会出现此错误:

TypeError: Attempted to assign to readonly property. MyTimer.js: 35

我知道显示此错误是因为我正在使用严格模式,但我启用了严格模式来帮助我调试此对象。

创建 MyTimer 单例的调用是:

var simTimer = new SimTimer();

然后我在 MyTimer 中添加一个要执行的任务,如下所示:

var task = function(){
    console.log("performing task.");
};

simTimer.addTask(task);

最后,这是 MyTimer 对象(第 35 行已标记):

var MyTimer = (function () {
    "use strict";

    // var timer;
    var tasks;

    /**
     * If an instance of MyTimer exists, it will be saved to this variable and returned
     * by any subsequent calls to this constructor, thus only one instance (stored in this
     * variable) will be accessible.
     * @private
     */
    var instance;

    /**
     * Called to initialize this MyTimer Object, or return #instance if it already contains
     * an instance of this Object.
     */
    function Singleton() {
        if (instance) {
            return instance;
        }
        instance = this;
        tasks = $.Callbacks();
        this.timer = setInterval(function()
        {
            this.tasks.fire();
        }, 1000);//<---- THIS IS LINE 35!

        this.addTask = function(task)
        {
            this.tasks.add(task);
        };

        this.removeTask = function(task)
        {
            this.tasks.remove(task);
        };
    }

    //instance accessor
    Singleton.getInstance = function () {
        return instance || new Singleton();
    };

    return Singleton();

}());

我没有掌握什么?我已经阅读了很多关于 Module Patterns 的文档,并且之前已经成功地编写了 Singletons - 那么我哪里出错了?

** 编辑:**

我能够通过删除 var tasks 并使用 thisSingleton 中创建它来获得正确的行为。该函数的工作版本现在如下所示:

function Singleton() {
    if (instance) {
        return instance;
    }
    instance = this;

    this.tasks = $.Callbacks();

    this.timer = setInterval(function(){
        instance.tasks.fire();
    }, 1000);
    this.removeTask = function(task)
    {
        instance.tasks.remove(task);
    };
    this.addTask = function(task)
    {
        instance.tasks.add(task);
    };

}

所以我仍然不完全理解 - 为什么这个更改修复了它?这毕竟是范围问题吗?

最佳答案

如果我没看错你的代码,那么你这里有范围问题

this.timer = setInterval(function()
{
    this.tasks.fire();  <-- this will be in window scope
}, 1000);

应该是

this.timer = setInterval(function()
{
    instance.tasks.fire(); 
}, 1000);

关于JavaScript 单例类型错误 : why does strict mode flag this?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15710366/

相关文章:

javascript - 删除/避免将目标链接添加到 URL

java - 在 Javascript 中获取 userPrincipal

javascript - AJAX 还是 socket.io?

javascript - 多种类型错误——混淆——将带有 jquery 的 css 添加到复选框

javascript - JSON 响应未在 Angularjs View 中显示

javascript - 将 Protractor 测试项目从 javascript 移植到 typescript 的步骤

jquery - 将值与 jquery 中的 JSON 数组值相匹配

javascript - 使用 javascript 从另一个页面(第 3 页)刷新页面(第 1 页)

javascript - 未捕获的类型错误 : Cannot read property 'toLowerCase' of undefined

python - TypeError: 无法在 python 的 SCRAPY 中创建对 'str' 对象的弱引用