Javascript作用域/闭包泄漏
抓取所有父作用域变量的javascript闭包,甚至不使用它Javascript作用域/闭包泄漏,javascript,scope,closures,Javascript,Scope,Closures,抓取所有父作用域变量的javascript闭包,甚至不使用它 function A() { var v = 'some heavy content'; this.foo = function(){ return function(){ // I don't use "v" variable here // Is there link to it anyway? // How to prevent memory leaks like this, if
function A() {
var v = 'some heavy content';
this.foo = function(){
return function(){
// I don't use "v" variable here
// Is there link to it anyway?
// How to prevent memory leaks like this, if so?
}
}
}
Upd:
一些自己的研究:
function A() {
var v = 'some heavy content';
this.foo = function(){
return function(){
return eval('v');
}
}
}
var a = new A();
var foo = a.foo();
a = null;
console.log(foo());//some heavy content
因为这里没有答案 保持示波器清洁的最佳方法是使用正确的原型: 对于上面的代码,它应该如下所示:
function A() {
var v = 'some heavy content';
}
A.prototype.foo = function(){
return function(){
//there is nothing about v here
};
}
我想,我可以使用A.prototype.foo=函数{}来实现它。。。或者没有其他方法,我应该一直使用它?我不明白你的问题。eval'v'不会被定义,因为它的父范围是我相信的窗口?我想我想要的。我想在这里进行一些优化:若闭包不使用父范围中的一些变量,那个么它可能会丢失。所以我希望eval'v'返回未定义的,但这不是js的工作方式:它在闭包作用域中存储不必要的数据,即使父作用域已经被破坏了。那么你是在尝试手动执行垃圾收集吗?我不认为你能用JavaScript做到这一点。