javascript - 关闭次数? (语义澄清)

标签 javascript closures

<分区>

考虑以下 JavaScript 片段:

<script>
function Ninja() {
   var feints = 0;
    this.getFeints = function() {
        return feints;
    }

    this.feint = function() {
        feints++;
    }

    this.increaseByTwo = function() {
        feints = feints + 2;
    } 
}

var ninja = new Ninja();
ninja.feint();

console.log(ninja.getFeints());  //outputs one
ninja.increaseByTwo();
console.log(ninja.getFeints());  // outputs three
</script>

我说上面的代码创建了四个闭包对吗

  • Ninja 的一个 - 这有点无关紧要。
  • 一个用于 Ninja 中的每个内部函数。这三个闭包中的每一个都指向同一件事。

或者 JavaScript 是否创建了两个闭包

  • 一个给 Ninja - 这有点无关紧要
  • 一个用于三个内部函数。三个内部函数共享同一个闭包。

最佳答案

所有三个内部函数都有一个指向相同环境的闭包,因此内部的变量也是如此。这通常是 the whole point of having closures :

In computer science, a closure (also lexical closure or function closure) is a function or reference to a function together with a referencing environment—a table storing a reference to each of the non-local variables (also called free variables) of that function.1 A closure—unlike a plain function pointer—allows a function to access those non-local variables even when invoked outside of its immediate lexical scope.

请注意,这是内存泄漏的常见来源,因为您并不总是知道您正在保留这些引用。

看看Google's Javascript Style Guide says about closures是什么.

One thing to keep in mind, however, is that a closure keeps a pointer to its enclosing scope. As a result, attaching a closure to a DOM element can create a circular reference and thus, a memory leak.

关于javascript - 关闭次数? (语义澄清),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12899685/

相关文章:

javascript - 使用尺寸属性时选择下拉菜单不同

java - 安卓/Java : Waiting until closure has completed running

javascript - 传单未能聚焦于 map ​​到标记坐标

javascript - 从 AJAX 调用 Controller 操作而不重定向用户

javascript - 将 Angularjs 代码包装在闭包中的正确方法是什么?

javascript - 检测脚本列表何时全部加载到 javascript 中(使用命名空间)。

ios - 使用闭包而不是 UIBarButtonItem 的选择器参数但不使用弱 self

javascript - 有没有办法在 Javascript 中返回一个外部函数?

php - 使用 PHP 缩小内联 JavaScript

php - 单击任何一个链接时要禁用的一组链接