如何通俗地解釋閉包的概念?

來源:互聯網
上載者:User
網上隨便搜一個閉包的解釋,動不動就長篇大論,各種專業名詞,又扯上了記憶體泄露,各種用法……
我不想瞭解那麼多沒用的,能不能簡單的告訴到底什麼是閉包,我不關心閉包怎麼就不能被銷毀,怎麼個指標指來指去的,看得我是越看頭越暈!!
我得理解就是:
(函數裡面有個局部變數,然後通過在把這個變數的值retrun給函數)
這個過程就是閉包特性了。這個用法是不是太常見了啊。。。怎麼那麼多大牛能寫出來那麼長的文章來

回複內容:

假設你現在有一個函數 f (x) = a + x

這個函數是不完整的,比如 f (1) = a + 1 你還差一個問題: a 是多少?

有兩個方法回答這個問題

第一種叫“動態範圍”,a的值決定於函數 調用時上下文中a的值,比如

a = 1;
v=f(1) ; 這裡v為2

動態範圍的問題是,函數每一次調用相同的參數未必返回相同的值,其傳回值還取決於內容相關的某些值

第二種是“詞法範圍”,a的值取決於函數 定義時上下文中的值

g (a) = lambda (x) a + x;
f = g(2)

這裡函數g返回一個和上面函數f形式一樣函數,a在此處為2,那麼執行

a = 1;
v=f(1) ;這裡v為3

因為f要“記住”自己定義時a的值為2,所以實現時

f (x) = a + x 和 a = 2 被打包在一塊,被稱為“閉包”,意思是它是完整獨立的,僅僅依靠調用時參數求值,不再依賴調用時的上下文

暈,寫完以後才發現我也寫了不少...可以這樣理解,因為『純』的函數是沒有狀態的,加入了閉包以後就變成有狀態的了,相對於一個有成員變數的類執行個體來說,閉包中的狀態值不是自己管理,可以認為是『上帝』在管理。

看下面這個 javascript 例子:
var counter = function() {var counter = 0return function() {return counter++}}var anotherCounter = counter()console.log(anotherCounter())console.log(anotherCounter())console.log(anotherCounter())
片面地講 閉包就是 “北京城”,一層一層的控制,皇宮的皇上看上城內的妹子就可以用,城內的漢子要麼用城內的妹子,要麼去城外 =。= 把資料和範圍綁定到一起就是閉包。可以學習下做下面幾道題:Learning Advanced JavaScript 通過引用變數從而阻止該變數被記憶體回收的機制將一個內容相關的私人變數的生命週期延長的機制搬運一下 @winter 的blog 閉包概念考證 · Issue #3 · wintercn/blog · GitHub
// One of JavaScript's most powerful features is closures. If a function is// defined inside another function, the inner function has access to all the// outer function's variables, even after the outer function exits.function sayHelloInFiveSeconds(name){    var prompt = "Hello, " + name + "!";    // Inner functions are put in the local scope by default, as if they were    // declared with `var`.    function inner(){        alert(prompt);    }    setTimeout(inner, 5000);    // setTimeout is asynchronous, so the sayHelloInFiveSeconds function will    // exit immediately, and setTimeout will call inner afterwards. However,    // because inner is "closed over" sayHelloInFiveSeconds, inner still has    // access to the `prompt` variable when it is finally called.}sayHelloInFiveSeconds("Adam"); // will open a popup with "Hello, Adam!" in 5s
var globalVal=null;var fn=function(){var a=1;globalVal=function(){a++;console.log(a);}}fn();globalVal();//2globalVal();//3
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.