您现在的位置: 365建站网 > 365文章 > JavaScript中的闭包

JavaScript中的闭包

文章来源:365jz.com     点击数:167    更新时间:2009-10-12 09:40   参与评论

Closures are functions whose lexical representation includes variables that aren’t evaluated, meaning that functions are capable of using variables defined outside of the function itself. Using global variables in ECMAScript is a simple example of a closure. Consider the following example:

var sMessage = “Hello World!”;
function sayHelloWorld() {
alert(sMessage);
}
sayHelloWorld();


In this code, the variable sMessage isn’t evaluated for the function sayHelloWorld() while the scripts is being loaded into memory. The function captures sMessage for later use, which is to say that the interpreter knows to check the value of sMessage when the function is called. When sayHelloWorld() is called (on the last line), the value of sMessage is assigned and the message “Hello World!” is displayed.
Closures can get more complicated, as when you are defining a function inside of another function, as shown here:

var iBaseNum = 8;
function addNumbers(iNum1, iNum2) {
function doAddition() {
return iNum1 + iNum2 + iBaseNum;
}
return doAddition();
}


Here, the function addNumbers() contains a function (the closure) named doAddition(). The internal function is a closure because it captures the arguments of the outer function, iNum1 and iNum2, as well as the global variable iBaseNum. The last step of addNumbers() calls the inner function, which adds the two arguments and the global variable and returns the value. The important concept to grasp here is that doAddition() doesn’t accept any arguments at all; the values it uses are captured from the execution environment.
As you can see, closures are a very powerful, versatile part of ECMAScript that can be used to perform complex calculations. Just as when you use any advanced functionality, exercise caution when using closures because they can get extremely complex.

Note:被称为Closure的function必须在其外层function的作用域范围内,即必须将其函数定义写在其外层函数的大括号内({})。

如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛

发表评论 (167人查看0条评论)
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
昵称:
最新评论
------分隔线----------------------------

快速入口

· 365软件
· 杰创官网
· 建站工具
· 网站大全

其它栏目

· 建站教程
· 365学习

业务咨询

· 技术支持
· 服务时间:9:00-18:00
365建站网二维码

Powered by 365建站网 RSS地图 HTML地图

copyright © 2013-2024 版权所有 鄂ICP备17013400号