Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

javascript - What are free variables?

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Free variables are simply the variables that are neither locally declared nor passed as parameter.

Source :

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...