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


Posted in Javascript onMay 08, 2007

原文出处: 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)
来解析的。

--------------------------------------------------------------------------------

到此可能你有这样的认识:

function f(x){return x*x;};f(x);==(function(x){return x*x;})(x);==(function(x){return x*x;}(x));

但是他们还是有区别的,
首先,对于像第二和第三种形式,其它的函数和代码是不可能调用所定义的函数的,有一种说发把这样的函数称为匿名函数或者函数直接量。
其次,第二和第三种形式执行的函数,中间变量不会污染到全局命名空间,你可以把中间的代码看作纯粹的子过程调用。
当然使用后面两种形式的函数定义可以很容易的实现闭包。
看一个例子:

/*
http://jibbering.com/faq/faq_notes/closures.html(Dnew.CN注)
A global variable - getImgInPositionedDivHtml - is declared and
  assigned the value of an inner function expression returned from
  a one-time call to an outer function expression.

  That inner function returns a string of HTML that represents an
  absolutely positioned DIV wrapped round an IMG element, such that
  all of the variable attribute values are provided as parameters
  to the function call:-
*/
var getImgInPositionedDivHtml = (function(){
   /* The - buffAr - Array is assigned to a local variable of the
      outer function expression. It is only created once and that one
      instance of the array is available to the inner function so that
      it can be used on each execution of that inner function.

      Empty strings are used as placeholders for the date that is to
      be inserted into the Array by the inner function:-
   */
   var buffAr = [
       '<div id="',
       '',   //index 1, DIV ID attribute
       '" style="position:absolute;top:',
       '',   //index 3, DIV top position
       'px;left:',
       '',   //index 5, DIV left position
       'px;width:',
       '',   //index 7, DIV width
       'px;height:',
       '',   //index 9, DIV height
       'px;overflow:hidden;\"><img src=\"',
       '',   //index 11, IMG URL
       '\" width=\"',
       '',   //index 13, IMG width
       '\" height=\"',
       '',   //index 15, IMG height
       '\" alt=\"',
       '',   //index 17, IMG alt text
       '\"><\/div>'
   ];
   /* Return the inner function object that is the result of the
      evaluation of a function expression. It is this inner function
      object that will be executed on each call to -
      getImgInPositionedDivHtml( ... ) -:-
   */
   return (function(url, id, width, height, top, left, altText){
       /* Assign the various parameters to the corresponding
          locations in the buffer array:-
       */
       buffAr[1] = id;
       buffAr[3] = top;
       buffAr[5] = left;
       buffAr[13] = (buffAr[7] = width);
       buffAr[15] = (buffAr[9] = height);
       buffAr[11] = url;
       buffAr[17] = altText;
       /* Return the string created by joining each element in the
          array using an empty string (which is the same as just
          joining the elements together):-
       */
       return buffAr.join('');
   }); //:End of inner function expression.
})();
/*^^- :The inline execution of the outer function expression. */

Javascript 相关文章推荐
textContent在Firefox下与innerText等效的属性
May 12 Javascript
为你的网站增加亮点的9款jQuery插件推荐
May 03 Javascript
js中数组(Array)的排序(sort)注意事项说明
Jan 24 Javascript
jquery实现的鼠标下拉滚动置顶效果
Jul 24 Javascript
2014最热门的JavaScript代码高亮插件推荐
Nov 25 Javascript
莱鸟介绍window.print()方法
Jan 06 Javascript
搭建Bootstrap离线文档的方法
Dec 02 Javascript
基于jQuery实现数字滚动效果
Jan 16 Javascript
详解angularjs跨页面传参遇到的一些问题
Nov 01 Javascript
微信小程序中使用Async-await方法异步请求变为同步请求方法
Mar 28 Javascript
vue-cli3自动消除console.log()的调试信息方式
Oct 21 Javascript
浅析VUE防抖与节流
Nov 24 Vue.js
阻止JavaScript事件冒泡传递(cancelBubble 、stopPropagation)
May 08 #Javascript
延时重复执行函数 lLoopRun.js
May 08 #Javascript
用js判断浏览器是否是IE的比较好的办法
May 08 #Javascript
[全兼容哦]--实用、简洁、炫酷的页面转入效果loing
May 07 #Javascript
javascript之水平横向滚动歌词同步的应用
May 07 #Javascript
javascript之ESC(第二类混淆)
May 06 #Javascript
通过Unicode转义序列来加密,按你说的可以算是混淆吧
May 06 #Javascript
You might like
php中session_unset与session_destroy的区别分析
2011/06/16 PHP
PHP中如何实现常用邮箱的基本判断
2014/01/07 PHP
PHP数据库操作三:redis用法分析
2017/08/16 PHP
一个多次搜索+多次传值的解决方案
2007/01/20 Javascript
在JavaScript中通过URL传递汉字的方法
2007/04/09 Javascript
js 解决“options为空或不是对象”
2008/12/22 Javascript
获取数组中最大最小值方法js代码(自写)
2013/08/12 Javascript
node.js中的fs.fchown方法使用说明
2014/12/16 Javascript
jQuery Validate表单验证入门学习
2015/12/18 Javascript
浅析Bootstrap缩略图组件与警示框组件
2016/04/29 Javascript
基于jQuery实现页面搜索功能
2020/03/26 Javascript
jQuery实现的背景颜色渐变动画效果示例
2017/03/24 jQuery
JavaScript实现音乐自动切换和轮播
2017/11/05 Javascript
jquery radio 动态控制选中失效问题的解决方法
2018/02/28 jQuery
JavaScript事件发布/订阅模式原理与用法分析
2018/08/21 Javascript
jQuery表单元素过滤选择器用法实例分析
2019/02/20 jQuery
ES6 Promise对象概念及用法实例详解
2019/10/15 Javascript
在Vue项目中,防止页面被缩放和放大示例
2019/10/28 Javascript
[00:35]可解锁地面特效
2018/12/20 DOTA
Python实现模拟时钟代码推荐
2015/11/08 Python
对Python 内建函数和保留字详解
2018/10/15 Python
python 列表转为字典的两个小方法(小结)
2019/06/28 Python
Flask框架模板渲染操作简单示例
2019/07/31 Python
使用python实现男神女神颜值打分系统(推荐)
2019/10/31 Python
使用pytorch实现论文中的unet网络
2020/06/24 Python
详解Flask前后端分离项目案例
2020/07/24 Python
Python 爬虫性能相关总结
2020/08/03 Python
简历的自荐信
2013/12/19 职场文书
欢送退休感言
2014/02/08 职场文书
事业单位人员的自我评价范文
2014/09/21 职场文书
2015年老干部工作总结
2015/04/23 职场文书
入党培养人考察意见
2015/06/08 职场文书
重阳节主题班会
2015/08/17 职场文书
2016年社区六一儿童节活动总结
2016/04/06 职场文书
python 使用Tensorflow训练BP神经网络实现鸢尾花分类
2021/05/12 Python
微信小程序调用python模型
2022/04/21 Python