国产探花免费观看_亚洲丰满少妇自慰呻吟_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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 阜平县| 固阳县| 商丘市| 台东市| 霍州市| 井研县| 元谋县| 盐源县| 广宁县| 安顺市| 辰溪县| 彩票| 夏津县| 新晃| 甘南县| 昌江| 大关县| 武义县| 洮南市| 东丰县| 驻马店市| 乌鲁木齐县| 财经| 长治县| 黄冈市| 临朐县| 怀安县| 贵德县| 筠连县| 明溪县| 名山县| 泾川县| 迭部县| 漳州市| 江都市| 交口县| 平昌县| 阜新市| 南澳县| 定州市| 泗阳县|