我是 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
并使用 this
在 Singleton
中创建它来获得正确的行为。该函数的工作版本现在如下所示:
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/