什么是自由变量? [英] What are free variables?
问题描述
JavaScript关闭定义说:
closure是一个表达式变量以及绑定这些变量
的环境(关闭表达式)。
我自由变量的概念?这个概念Javascript是特定的还是应用于其他语言?
自由变量只是既不是本地声明也不是传递作为参数。
在计算机编程中,术语自由变量是指在函数中使用的变量
,它们不是局部变量,也不是
函数的参数。 1 术语非本地变量通常是此
上下文中的同义词。
在javascript闭包中,这些只是函数在声明闭包或在父范围中的封闭范围中读取和写入的变量。 / p>
看看这个真实的例子:
Gol.prototype._ensureInit = function(){
...
var _this = this;
var setDim = function(){
_this.w = _this.canvas.clientWidth;
_this.h = _this.canvas.clientHeight;
_this.canvas.width = _this.w;
_this.canvas.height = _this.h;
_this.dimChanged = true;
_this.draw();
};
setDim();
window.addEventListener('resize',setDim);
...
};
在这个例子中,一个闭包从 setDim
函数指向在封闭范围( _ensureInit
函数)中声明的变量 _this
。此变量不在 setDim
中声明,也不传递。这是一个自由变量。
请注意, _this
不会成为函数 setDim
:在同一作用域中声明的另一个函数将共享同一个变量。
Javascript closure definition says :
A "closure" is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).
Can some one explain to me the concept of free variables ? Is this concept Javascript specific or applies to other languages also ?
Free variables are simply the variables that are neither locally declared nor passed as parameter.
In computer programming, the term free variable refers to variables used in a function that are not local variables nor parameters of that function.1 The term non-local variable is often a synonym in this context.
In javascript closures, those are simply the variables that the function takes (read and write) in the enclosing scope where is declared the closure or in a parent scope.
Look at this real world example :
Gol.prototype._ensureInit = function() {
...
var _this = this;
var setDim = function() {
_this.w = _this.canvas.clientWidth;
_this.h = _this.canvas.clientHeight;
_this.canvas.width = _this.w;
_this.canvas.height = _this.h;
_this.dimChanged = true;
_this.draw();
};
setDim();
window.addEventListener('resize', setDim);
...
};
In this example a closure points from the setDim
function towards the variable _this
declared in the enclosing scope (the _ensureInit
function). This variable isn't declared in setDim
nor passed. It's a "free variable".
Note that _this
doesn't become a variable of the function setDim
: another function declared in the same scope would share the same variable.
这篇关于什么是自由变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!