易截截图软件、单文件、免安装、纯绿色、仅160KB

JavaScript中匿名函数,函数直接量和闭包(转)

原文出处: http://www.dnew.cn/post/196.htm
先看下下面几种写法
1.function f(x){return x*x;};f(x);
2.(function(x){return x*x;})(x);
3.(function(x){return x*x;}(x));
第一种我们应该都很熟悉了,这是我们经常使用的写法。第二第三种都是匿名函数的写法。
--------------------------------------------------------------------------------
第二种
可以这样理解:
•var f=function(x) {return x*x;};f()
那我们不通过f这个变量来引用函数就是
•function(){}()
然而这样肯定是错误的就像
•var f=1+2;
•f=f*0;

•var f=1+2*0;
结果不同一样。
要得到正确结果只能:
•f=(1+2)*0;
也就是要明确的标识出程序块,即:
•(function(){})()
肯你有疑问:括号“()”到底是不是起到了标识代码块的作用?
我们可以用JavaScript的内置函数检测一下!
举一个最简单的例子:
•alert(4)
这段代码会弹出提示内容是“4”
改成这样
•(alert)(4)
可以看到执行的效果和上一段代码一样。
这种形式的函数执行也被很多JavaScript框架所采用。
--------------------------------------------------------------------------------
第三种,如果你用过jsvm框架的话就会发现里面的代码使用了这种形式。
那如何解释第三种情况呢?
为了弄明白浏览器是如何理解这样的写法的,我们可以利用一下Mozilla Firefox的错误控制台功能。
在代码中插入一段错误代码,代码段如下:
•(function(s){s+s}(1)).splice();
打开Mozilla Firefox的错误控制台,可以看到有如下的错误提示
错误: (function (s) {})(1) has no properties
源文件:file:///C:/Documents…….html
行:18
可以认为,浏览器对于
•(function(s){s+s}(1))
这样的代码按照
•(function (s) {s+s})(1)
来解析的。


相关文档:

[翻译]High Performance JavaScript(027)

第九章
Building and Deploying High-Performance JavaScript Applications
创建并部署高性能JavaScript应用程序
    According to a 2007 study by Yahoo!'s Exceptional Performance team, 40%–60% of Yahoo!'s users have an empty cache experience, and about 20% of all page views are done ......

[翻译]High Performance JavaScript(028)

JavaScript Minification  JavaScript紧凑
    JavaScript minification is the process by which a JavaScript file is stripped of everything that does not contribute to its execution. This includes comments and unnecessary whitespace. The process typically reduces the file size by ha ......

[翻译]High Performance JavaScript(029)

Working Around Caching Issues  关于缓存问题
    Adequate cache control can really enhance the user experience, but it has a downside: when revving up your application, you want to make sure your users get the latest version of the static content. This is accomplished by renaming ......

用JavaScript写的小时候玩的乒乓球小游戏

由于火狐浏览器不支持“removeNode”函数,所以一下代码只支持IE.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
< ......

JavaScript 调用表单重置方法


1 history.go(0)  
2 location.reload() (页面进行刷新,但为disabled的元素的值不会被清空)
3 location=location 
4 location.assign(location) 
5 location.replace(location) 
6 from..reset()  (页面不进行刷新,模拟单击对所调用表单重置按钮的单击)
......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号