国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

js閉包學習心得總結

2019-11-19 14:01:21
字體:
來源:轉載
供稿:網友

首先引用來自官網文檔的定義:

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 阿克苏市| 阳山县| 龙山县| 明星| 龙游县| 永康市| 黄山市| 民权县| 南和县| 沁水县| 高淳县| 邮箱| 南江县| 利川市| 宁化县| 外汇| 雷波县| 昌邑市| 青神县| 鄱阳县| 千阳县| 东阳市| 潜江市| 洛南县| 栾城县| 虞城县| 南召县| 沙雅县| 疏勒县| 老河口市| 玉溪市| 莒南县| 休宁县| 泸西县| 全南县| 兰州市| 龙州县| 江津市| 格尔木市| 大埔区| 祁东县|