考虑以下 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.