javascript - AngularJS 闭包内存泄漏?

标签 javascript angularjs memory-leaks

作为 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/

相关文章:

c - 子进程中fork()后泄漏,为什么?

javascript - 如何在 jQuery Mobile 中正确定位元素?

javascript - 在 jqGrid 中只加载可选择的列

使用国际键盘输入印地语的 JavaScript 库

javascript - 带参数的简单 $http.get 请求

javascript - 如何在 Protractor 中截取整个页面的屏幕截图?

javascript - JavaScript 对象的生命周期和内存泄漏

javascript - 从 JavaScript 控制台查找和操作 React.js 组件

javascript - 删除带有按钮的输入表单失败

ios - 使用 block 的内存泄漏