(轉(zhuǎn)載)JavaScript中匿名函數(shù),函數(shù)直接量和閉包
更新時(shí)間:2007年05月08日 00:00:00 作者:
原文出處: 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));
第一種我們應(yīng)該都很熟悉了,這是我們經(jīng)常使用的寫法。第二第三種都是匿名函數(shù)的寫法。
--------------------------------------------------------------------------------
第二種
可以這樣理解:
var f=function(x) {return x*x;};f()
那我們不通過f這個(gè)變量來引用函數(shù)就是
function(){}()
然而這樣肯定是錯(cuò)誤的就像
var f=1+2;
f=f*0;
與
var f=1+2*0;
結(jié)果不同一樣。
要得到正確結(jié)果只能:
f=(1+2)*0;
也就是要明確的標(biāo)識(shí)出程序塊,即:
(function(){})()
肯你有疑問:括號(hào)“()”到底是不是起到了標(biāo)識(shí)代碼塊的作用?
我們可以用JavaScript的內(nèi)置函數(shù)檢測(cè)一下!
舉一個(gè)最簡單的例子:
alert(4)
這段代碼會(huì)彈出提示內(nèi)容是“4”
改成這樣
(alert)(4)
可以看到執(zhí)行的效果和上一段代碼一樣。
這種形式的函數(shù)執(zhí)行也被很多JavaScript框架所采用。
--------------------------------------------------------------------------------
第三種,如果你用過jsvm框架的話就會(huì)發(fā)現(xiàn)里面的代碼使用了這種形式。
那如何解釋第三種情況呢?
為了弄明白瀏覽器是如何理解這樣的寫法的,我們可以利用一下Mozilla Firefox的錯(cuò)誤控制臺(tái)功能。
在代碼中插入一段錯(cuò)誤代碼,代碼段如下:
(function(s){s+s}(1)).splice();
打開Mozilla Firefox的錯(cuò)誤控制臺(tái),可以看到有如下的錯(cuò)誤提示
錯(cuò)誤: (function (s) {})(1) has no properties
源文件:file:///C:/Documents…….html
行:18
可以認(rèn)為,瀏覽器對(duì)于
(function(s){s+s}(1))
這樣的代碼按照
(function (s) {s+s})(1)
來解析的。
--------------------------------------------------------------------------------
到此可能你有這樣的認(rèn)識(shí):
function f(x){return x*x;};f(x);==(function(x){return x*x;})(x);==(function(x){return x*x;}(x));
但是他們還是有區(qū)別的,
首先,對(duì)于像第二和第三種形式,其它的函數(shù)和代碼是不可能調(diào)用所定義的函數(shù)的,有一種說發(fā)把這樣的函數(shù)稱為匿名函數(shù)或者函數(shù)直接量。
其次,第二和第三種形式執(zhí)行的函數(shù),中間變量不會(huì)污染到全局命名空間,你可以把中間的代碼看作純粹的子過程調(diào)用。
當(dāng)然使用后面兩種形式的函數(shù)定義可以很容易的實(shí)現(xiàn)閉包。
看一個(gè)例子:
/*
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. */
先看下下面幾種寫法
1.function f(x){return x*x;};f(x);
2.(function(x){return x*x;})(x);
3.(function(x){return x*x;}(x));
第一種我們應(yīng)該都很熟悉了,這是我們經(jīng)常使用的寫法。第二第三種都是匿名函數(shù)的寫法。
--------------------------------------------------------------------------------
第二種
可以這樣理解:
var f=function(x) {return x*x;};f()
那我們不通過f這個(gè)變量來引用函數(shù)就是
function(){}()
然而這樣肯定是錯(cuò)誤的就像
var f=1+2;
f=f*0;
與
var f=1+2*0;
結(jié)果不同一樣。
要得到正確結(jié)果只能:
f=(1+2)*0;
也就是要明確的標(biāo)識(shí)出程序塊,即:
(function(){})()
肯你有疑問:括號(hào)“()”到底是不是起到了標(biāo)識(shí)代碼塊的作用?
我們可以用JavaScript的內(nèi)置函數(shù)檢測(cè)一下!
舉一個(gè)最簡單的例子:
alert(4)
這段代碼會(huì)彈出提示內(nèi)容是“4”
改成這樣
(alert)(4)
可以看到執(zhí)行的效果和上一段代碼一樣。
這種形式的函數(shù)執(zhí)行也被很多JavaScript框架所采用。
--------------------------------------------------------------------------------
第三種,如果你用過jsvm框架的話就會(huì)發(fā)現(xiàn)里面的代碼使用了這種形式。
那如何解釋第三種情況呢?
為了弄明白瀏覽器是如何理解這樣的寫法的,我們可以利用一下Mozilla Firefox的錯(cuò)誤控制臺(tái)功能。
在代碼中插入一段錯(cuò)誤代碼,代碼段如下:
(function(s){s+s}(1)).splice();
打開Mozilla Firefox的錯(cuò)誤控制臺(tái),可以看到有如下的錯(cuò)誤提示
錯(cuò)誤: (function (s) {})(1) has no properties
源文件:file:///C:/Documents…….html
行:18
可以認(rèn)為,瀏覽器對(duì)于
(function(s){s+s}(1))
這樣的代碼按照
(function (s) {s+s})(1)
來解析的。
--------------------------------------------------------------------------------
到此可能你有這樣的認(rèn)識(shí):
function f(x){return x*x;};f(x);==(function(x){return x*x;})(x);==(function(x){return x*x;}(x));
但是他們還是有區(qū)別的,
首先,對(duì)于像第二和第三種形式,其它的函數(shù)和代碼是不可能調(diào)用所定義的函數(shù)的,有一種說發(fā)把這樣的函數(shù)稱為匿名函數(shù)或者函數(shù)直接量。
其次,第二和第三種形式執(zhí)行的函數(shù),中間變量不會(huì)污染到全局命名空間,你可以把中間的代碼看作純粹的子過程調(diào)用。
當(dāng)然使用后面兩種形式的函數(shù)定義可以很容易的實(shí)現(xiàn)閉包。
看一個(gè)例子:
/*
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. */
相關(guān)文章
短視頻(douyin)去水印工具的實(shí)現(xiàn)代碼
這篇文章主要介紹了市面上短視頻(douyin)"去水印"的工具原來是這樣實(shí)現(xiàn)的,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-03-03
你必須了解的JavaScript中的屬性描述對(duì)象詳解(下)
JavaScript提供了一個(gè)內(nèi)部數(shù)據(jù)結(jié)構(gòu),用來描述對(duì)象的屬性,控制它的行為,比如該屬性是否可寫、可遍歷等等。這個(gè)內(nèi)部數(shù)據(jù)結(jié)構(gòu)稱為“屬性描述對(duì)象”。本文主要帶大家了解一下JavaScript中你必須了解的屬性描述對(duì)象,需要的可以參考一下2022-12-12
javascript模擬地球旋轉(zhuǎn)效果代碼實(shí)例
javascript模擬地球旋轉(zhuǎn)效果,把一下代碼保存到HTML文件,打開就可以看到一個(gè)旋轉(zhuǎn)的地球。請(qǐng)使用Chrome、Opera或者火狐瀏覽器查看,IE8不支持2013-12-12
Bootstrap每天必學(xué)之彈出框(Popover)插件
Bootstrap每天必學(xué)之彈出框(Popover)插件,彈出框的內(nèi)容完全可使用 Bootstrap 數(shù)據(jù) API(Bootstrap Data API)來填充,如何實(shí)現(xiàn)請(qǐng)參考本文2016-04-04
JavaScript實(shí)現(xiàn)小程序圖片裁剪功能的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何利用JavaScript實(shí)現(xiàn)小程序圖片裁剪功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起了解一下2023-03-03
JavaScript使用AutoDecimal解決運(yùn)算精度問題
這篇文章主要介紹了?JavaScript?運(yùn)算中的精度問題及解決方案?AutoDecimal,指出?JavaScript?處理浮點(diǎn)數(shù)運(yùn)算常出現(xiàn)精度問題,現(xiàn)有解決方案存在不足,為了解決這一問題,AutoDecimal?應(yīng)運(yùn)而生,本文給大家介紹了JavaScript使用AutoDecimal解決運(yùn)算精度問題2024-12-12

