首頁 > web前端 > js教程 > 主體

js閉包使用詳解

php中世界最好的语言
發布: 2018-04-28 11:56:39
原創
1604 人瀏覽過

這次帶給大家js閉包使用詳解,js閉包使用的注意事項有哪些,下面就是實戰案例,一起來看一下。

closure is the combination of a function and the lexical environment within which that function was declared.

閉包是一個函數和其內部公開變量的環境的集合.

簡單而言,閉包= 函數環境

第一個閉包的範例

function init() {
 var name = 'Mozilla'; // name is a local variable created by init
 function displayName() { // displayName() is the inner function, a closure
 alert(name); // use variable declared in the parent function 
 }
 displayName(); 
}
init();
because inner functions have access to the variables of outer functions, displayName() can access the variable name declared in the parent function, init().
登入後複製

其實這個栗子很簡單,displayName( )就是init()內部的閉包函數,而為啥在displayName內部可以呼叫到外部定義的變數name 呢,因為js內部函數有取得外部函數中變數的權限。

第二個範例

var data = [
 {'key':0},
 {'key':1},
 {'key':2}
];
function showKey() {
 for(var i=0;i<data.length;i++) {
   setTimeout(function(){
    //console.log(i); //发现i输出了3次3
   //console.log(this); // 发现 this 指向的是 Window
   data[i].key = data[i].key + 10;
   console.log(data[i].key)
   }, 1000);
 }
}
showKey();
登入後複製

上面這個範例可以正確輸出 10 11 12 嗎?

答案是:並不能,還會報語法錯誤....

console.log(i); 發現i輸出了3次3,也就是說,在setTimeout 1000毫秒之後,執行閉包函數的時候,for循環已經執行結束了,i是固定值,並沒有實現我們期望的效果。

console.log(this); 發現this 指向的是Window,也就是說,在函數內部實現的閉包函數已經被轉變成了全域函數,儲存到了記憶體中。

所以需要再定義一個執行函數

var data = [
 {'key':0},
 {'key':1},
 {'key':2}
];
function showKey() {
 var f1 = function(n){
  data[i].key = data[i].key + 10;
  console.log(data[i].key)
 }
 for(var i=0;i<data.length;i++) {
   setTimeout(f1(i), 1000);
 }
}
showKey();
// 得到预期的 10 11 12
登入後複製

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

Vue自訂動態元件使用詳解

js使用分時函數步驟詳解

以上是js閉包使用詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!