什么是闭包呢? [英] What are the closures for exactly?
问题描述
我一直在阅读关于closures和javascript,我想我有它,直到我试过这个:
I have been reading about closures and javascript, and I thought I got it, till I tried this:
var Object5 = function (param) {
var x = 0;
var squareBrace = function () {
return '[' + param + x + ']';
};
this.toString = function () {
x = x + 1;
return squareBrace();
};
};
然后我运行这个代码:
var counter = new Object5("Counter: ");
print("Has x:" + ('x' in counter));
print("Has f:" + ('f' in counter));
print("Can access x:" + (!!counter.x));
print("Can Invoke f:" + (!!counter.f));
print(counter.toString());
print(counter.toString());
print(counter.toString());
print(counter.toString());
print(counter.toString());
print(counter.toString());
这是我得到的:
Has x:false
Has f:false
Can access x:false
Can Invoke f:false
[Counter: 1]
[Counter: 2]
[Counter: 3]
[Counter: 4]
[Counter: 5]
[Counter: 6]
我想我会得到一个TypeError,因为'x'和'f'将是'undefined'它工作。我认为闭包是为了使这种行为,'x'和'y'是'私人的,没有关闭这些成员将被遗忘。
I thought I would get a 'TypeError' because 'x' and 'f' would be 'undefined', but then I got it working. I thought closures were for enable this behavior, 'x' and 'y' are 'private' and without a closure those member would be forgotten.
显然我得到了
可以请别人告诉我什么是关闭,然后为什么这个工作?
Could please somebody tell me what are closures for then and why this work?
感谢。
推荐答案
闭包是一种这是一种将在一个作用域中定义的参数拉到另一个作用域中的方法。
A closure is a scoping technique. It's a way of pulling a parameter defined in one scope into another scope. When you do
var x = 1;
var f = function(){
console.log(x); // you've just 'closed in' the variable x.
};
f();
x
在你的具体实例中,有两个变量是封闭的: param
x
它们绑定到您定义的函数的作用域。当执行 toString
时,您在 x
中递增关闭。当 toString
执行 squareBrace
时,该方法使用 x
param
。所以你有两个围绕变量 x
的闭包,每个方法都有一个闭包(它也在对象本身的范围内)
In your specific instance, 2 variables are closed-in: param
and x
. They are bound to the scope of the functions you defined. When you execute toString
, your are incrementing the closed in x
. When toString
executes squareBrace
, that method uses both x
and param
. So you have 2 closures around the variable x
, one for each method (its also in the scope of the object itself)
这篇关于什么是闭包呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!