Pen*_*per 6 javascript lambda memory-leaks scope setinterval
我现在想知道是否有更好的解决方案,而不是通过参数'e' 将此范围传递给lambda函数,然后使用call()将其传递给'funkyFunction' - 方法
setInterval(function(e){e.funkyFunction.call(e)}, speed, this)
Run Code Online (Sandbox Code Playgroud)
(抛出一些小问题:我一直在阅读有关javascript内存泄漏的内容.lambda函数如何影响我的内存?首先定义它var i = function(e)...
然后将其作为参数传递给setInterval 更好吗?)
我的情况可能有点不同,但这就是我所做的:
var self = this;
setInterval(function() { self.func() }, 50);
Run Code Online (Sandbox Code Playgroud)
我的情况是我的代码在一个类方法中,我需要保持正确的范围,因为我不希望'this'绑定解析到当前窗口.
例如.我想使用setInterval从MyClass.init运行MyClass.animate,所以我将这个scope-keep代码放入MyClass.init
您可以使用本机绑定功能.
function Loop() {
this.name = 'some name for test';
setInterval( (function(){//wrap the function as object
//after bind, "this" is loop refference
console.log(this);
}).bind(this), 1000 );// bind the object to this (this is Loop refference)
}
var loop = new Loop();
Run Code Online (Sandbox Code Playgroud)
将此示例粘贴到控制台中以查看结果
仅依靠外部作用域定义的变量有什么问题?
(function() {
var x = {};
setInterval(function() {
funkyFunction.call(x)
}, speed);
})();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13137 次 |
最近记录: |