我担心我可能会使用泄漏内存的代码模式。下面是伪代码示例:重命名'this'关键字
window.user = new User();
user.getBasicInfo(function(basicInfo){
user.name = basicInfo.name;
user.getDetailedInfo(function(detailedInfo){
user.favoriteColor = detailedInfo.favoriteColor;
});
});
换句话说,我不使用'this'
关键字来引用用户对象;我直接指的是存储在window
对象内的user
对象。
很显然,关键字JavaScript 'this'
给了很多人很多麻烦。我见过一些人重新命名'this'
以使其更清晰,因为他们下降一个作用域链:
window.user = new User();
user.getBasicInfo(function(basicInfo){
var userInOuterScope = this;
userInOuterScope.name = basicInfo.name;
userInOuterScope.getDetailedInfo(function(detailedInfo){
var userInInnerScope = this;
userInInnerScope.favoriteColor = detailedInfo.favoriteColor;
});
});
不漂亮,但似乎作用域链可能会在这种情况下,少令人费解。
第一种方法可以泄漏内存吗?第二个可以吗?为了避免内存泄漏,我必须通过所有内容作为参数(并且永远不会引用当前范围之外的对象)?
谢谢,尖尖 - 我想我不确定何时在函数体内释放(或不释放)变量的引用。如果引用是通过“参数”对象传递的,我想在执行正文时很容易释放它。我担心,如果我通过循环访问'arguments'对象来引用变量,那么引用可能会持续存在,从而将函数体保留在内存中。 – marclar
我会用更多的信息更新答案。 – Pointy
感谢编辑,Pointy。我的大部分代码都是不显眼的,但是我有*一些内联JS,我会寻找迁移到jQuery.live处理程序。 – marclar