来自codewars上的一道题目的答案池里的一个答案,我感到有点疑惑:
为什么里面的 tryCode.test 在函数调用结束之后没有被回收呢?
函数最后return过来的不是只是数据么,这个“变量”(函数的属性?)应该不会给返回的吧。
MaximeDesRoches
function tryCode(indications) {
if(indications == null) {
tryCode.test = [5,5,5];1⃣️
return tryCode.test;
}
return tryCode.test = tryCode.test.map(function(c, i){
if (indications[i] === 0) return c;
return (indications[i] === 1) ? ++c : --c;
});
}
(这个函数会被反复调用,一开始是null,之后是数组。)
感觉机制上和闭包有点像,可是感觉不太一样啊。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
tryCode.test不是闭包,就是简单的在一个Function实例tryCode上动态添加了test属性而已函数返回时确实返回的是数据,但是这个数据已经赋值给了
tryCode.test,而tryCode.test把问题简化一下: