JavaScript 的closure 和 hoisting

來源:互聯網
上載者:User

標籤:glob   space   length   addclass   這一   全域   coff   代碼   nes   

閉包(closure)

當聲明一個函數時,其內部的變數的聲明也在它的scope中被截獲。比如下面的代碼中,變數 x 綁定到了外部scope的值,然後對 x 的引用在bar的上下文中被截獲。

var x = 4; // declaration in outer scopefunction bar() {    console.log(x); // outer scope is captured on declaration}bar(); // prints 4 to console

“截獲”的概念很有意思,因為我們可以從外層scope使用和修改變數,甚至外層scope已經不存在了,比如:

function foo() {    var x = 4; // declaration in outer scope    function bar() {        console.log(x); // outer scope is captured on declaration    }    return bar;    // x goes out of scope after foo returns}var barWithX = foo();barWithX(); // we can still access x

上面的例子中,當foo() 被調用時,其上下文在函數 bar() 中被截獲。所以在它返回之後, bar() 仍然可以訪問和修改變數 x。函數 foo(),其上下文在另一個函數中被截獲,叫做閉包。

  • 私人資料
    讓我們做一些有意思的事,比如定義private變數,讓它只對特定的函數可見:
function makeCounter() {    var counter = 0;    return {        value: function () {            return counter;        },        increment: function () {            counter++;        }    };}var a = makeCounter();var b = makeCounter();a.increment();console.log(a.value());console.log(b.value());

輸出

10

當 makeCounter() 被調用時,這個函數的快照會被儲存。所有其內部的代碼在執行過程中都使用這份快照。兩次調用建立兩個不同的快照,每個快照都有自己的counter變數。

  • IIFE
    閉包也用於防止全域全名空間的汙染,通常通過IIFE做到這一點。
    IIFE是特殊的閉包,在聲明之後立即調用。
    假設我們想用 “$” 引用 jQuery,考慮下面的方法,不用IIFE。
var $ = jQuery;// we‘ve just polluted the global namespace by assigning window.$ to jQuery

下面的例子中,IIFE用於確保 “$” 綁定到了閉包建立的 jQuery。

(function ($) {    // $ is assigned to jQuery here})(jQuery);// but window.$ binding doesn‘t exist, so no pollution
Hoisting

Hoisting是這樣一個機制,把所有變數和函數的聲明移動到它們的scope的頂部,但是,賦值仍然發生在聲明的地方。比如:

    console.log(foo);    // - > undefined    var foo = 42;    console.log(foo);    // - > 42

上面的代碼相當於:

    var foo; // Hoisted variable declaration    console.log(foo);    // - > undefined    foo = 42; // variable assignment remains in the same place    console.log(foo);    // - > 42

注意因為上面的undefined 與運行下面代碼得到的 not defined 不同:

    console.log(foo);    // - > foo is not defined 

類似的理念也適用於函數。當函數被賦值給一個變數時,變數的聲明就被hoisted了,而賦值還發生在原處。下面的兩塊代碼是一樣的:

    console.log(foo(2, 3));    // - > foo is not a function    var foo = function(a, b) {        return a * b;    }
    var foo;    console.log(foo(2, 3));    // - > foo is not a function    foo = function(a, b) {        return a * b;    }

當聲明function statements時,是不同的情境,不像function statements,函數的聲明在它自己的scope內被hoisted,看下面的代碼:

    console.log(foo(2, 3));    // - > 6    function foo(a, b) {        return a * b;    }

上面的代碼與下面的相同:

    function foo(a, b) {        return a * b;    }    console.log(foo(2, 3));    // - > 6

下面的例子解釋了hoisting是什麼,hoisting不是什麼

// (A) valid code:foo();function foo() {}// (B) **invalid**:bar(); TypeError: bar is not a functionvar bar = function () {};// (C) valid:foo();function foo() {    bar();}function bar() {}// (D) **invalid**:foo();function foo() {    bar(); // TypeError: bar is not a function}var bar = function () {};// (E) valid:function foo() {    bar();}var bar = function(){};foo();

JavaScript 的closure 和 hoisting

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.