gpt4 book ai didi

javascript - JS模块模式-为什么私有(private)变量没有被删除

转载 作者:行者123 更新时间:2023-12-03 12:25:48 25 4
gpt4 key购买 nike

我正在学习 Javascript 的模块模式。下面是“篮子”模块的示例。

我想我明白这是一个执行的匿名函数,因此您无法访问其中的变量,只能访问它返回的内容。为什么匿名函数执行完毕后,该函数内的变量和函数没有被删除/垃圾回收? JS 如何知道将它们保留在内存中以供以后使用?是因为我们返回了一个可以访问它们的函数吗?

var basketModule = (function () {

// privates

var basket = [];

function doSomethingPrivate() {
//...
}

function doSomethingElsePrivate() {
//...
}

// Return an object exposed to the public
return {

// Add items to our basket
addItem: function( values ) {
basket.push(values);
},

// Get the count of items in the basket
getItemCount: function () {
return basket.length;
},

// Public alias to a private function
doSomething: doSomethingPrivate,

// Get the total value of items in the basket
getTotal: function () {

var q = this.getItemCount(),
p = 0;

while (q--) {
p += basket[q].price;
}

return p;
}
};
})();

最佳答案

只要有一个对象的引用,它就不会被垃圾回收。

用 JavaScript 术语来说,上面的代码创建了一个闭包,有效地将外部值捕获到内部函数中。

这是一个简短的关闭示例:

var test = (function() {
var k = {};

return function() {
// This `k` is trapped -- closed over -- from the outside function and will
// survive until we get rid of the function holding it.
alert(typeof k);
}
}());

test();
test = null;
// K is now freed to garbage collect, but no way to reach it to prove that it did.

此处提供了更长的讨论:
How do JavaScript closures work?

关于javascript - JS模块模式-为什么私有(private)变量没有被删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24216856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com