同じ質問がありましたが、組み込みのソリューションはないようです。
function setScopedInterval(func, millis, scope) {
return setInterval(function () {
func.apply(scope);
}, millis);
}
利用方法:
function MyClass() {
this.timer = null;
this.myFunc = function() { console.log('do some stuff'); };
this.run = function() {
this.timer = setScopedInterval(function () { this.myFunc(); }, 1000, this);
};
this.stop = function() { clearInterval(this.timer); };
}
var instance = new MyClass();
instance.run(); // will log to console every second
// until this line is called
instance.stop();
これは、実行されるコードの文字列ではなく、実際の関数を渡すユースケースのみを対象としています。
この機能を使用する際のメモリ リークに関する質問についてsetInterval
は、無名関数自体を使用する場合ほど問題はありません。ラムダ内のオブジェクトへの参照を使用する場合、この参照は、無名関数が存在する限り、参照されたオブジェクトをメモリに保持します。への呼び出しで関数が破棄されていると思いますclearInterval
。
最初に関数を変数に割り当てることによる利点はないと思います。逆に、anon関数が存在する限り、ガベージコレクションされない参照を含む別の変数が作成されます...