gpt4 book ai didi

javascript - AngularJS 闭包内存泄漏?

转载 作者:行者123 更新时间:2023-12-03 08:38:31 26 4
gpt4 key购买 nike

作为 AngularJS 的新手,我想了解有关 AngularJS 中的闭包以及如何使用它们来避免内存泄漏的更多信息。

我是否认为以下代码会泄漏内存,因为回调函数没有释放对 func1、func2 和 foo 的引用?

angular
.module('Mod1').
.controller('Ctrl1', ['$scope', 'foo', 'Service1', function($scope, foo, Service1) {

var func1 = function() {
// do stuff
}

$scope.func2 = function() {
// do more stuff
}

Service1.loadData().then(function(data) {
func1();
$scope.func2();
foo.func3();
});

$scope.$watch('blah', function() {
func1();
$scope.func2();
foo.func3();
});
}]);

或者回调会在作用域销毁时自动释放,从而删除对 func1、func2 和 foo 的最后引用吗?

最佳答案

当作用域对象无法访问并且不再被其他对象或函数引用时,Javascript 将清理作用域和回调函数。

Mark-and-sweep algorithm

This algorithm reduces the definition of "an object is not needed anymore" to "an object is unreachable".

This algorithm assumes the knowledge of a set of objects called roots (In JavaScript, the root is the global object). Periodically, the garbage-collector will start from these roots, find all objects that are referenced from these roots, then all objects referenced from these, etc. Starting from the roots, the garbage collector will thus find all reachable objects and collect all non-reachable objects.

关于javascript - AngularJS 闭包内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33123451/

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