私は JavaScript に比較的慣れていないため、このエラーが発生する理由を理解するのに苦労しています。
TypeError: readonly プロパティに割り当てようとしました。MyTimer.js: 35
strict モードを使用しているため、このエラーが表示されることは理解していますが、このオブジェクトのデバッグに役立つようにstrict モードを有効にしました。
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に関する多くのドキュメントを読み、以前にシングルトンを正常に作成したことがあります。ここでどこが間違っているのでしょうか?
** 編集: **
を削除し、を使用してvar tasks
作成することで、正しい動作を得ることができました。関数の作業バージョンは次のようになります。Singleton
this
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);
};
}
だから私はまだ完全には理解していません - なぜこの変更はそれを修正したのですか? 結局スコープの問題でしたか?