【发布时间】:2020-09-23 13:11:13
【问题描述】:
如果我有一个“接受”两个参数的函数sum,则返回一个将在“长时间”内解决的承诺。传递给sum 的任何参数(经过前两个参数)是否会保留在内存中,并且不会被垃圾回收?
例如,sum 会阻止“大对象”FOO 被垃圾回收吗?
const sum = (a, b) => new Promise((resolve) => {
setTimeout(() => resolve(a+b), 500 /* Lets pretend this is a huge number */);
});
(async () => {
const s = await sum(2, 3, {/* Some large object, FOO */});
console.log(s);
})();
我假设因为您可以通过“参数”对象访问 FOO,那么 FOO 是否需要保存在内存中?但是,由于箭头函数中无法访问“参数”,因此关键字函数和箭头函数之间的这种行为会有所不同吗?
function sum(a, b) {
return new Promise((resolve) => {
setTimeout(() => {
console.log(...arguments);
resolve(a+b);
}, 500 /* Lets pretend this is a huge number */);
});
};
const arrowSum = (a, b) => {
return new Promise((resolve) => {
setTimeout(() => {
console.log(...arguments);
resolve(a+b);
}, 500 /* Lets pretend this is a huge number */);
});
};
(async () => {
const s = await sum(2, 3, {/* Some large object, FOO */});
console.log(s);
const arrowS = await arrowSum(2, 3, {/* Some large object, FOO */});
console.log(arrowS);
})();
【问题讨论】:
标签: javascript garbage-collection arguments