JavaScript中的閉包介紹_javascript技巧

來源:互聯網
上載者:User

所謂的閉包應該是指: 內建函式讀取當前函數以外的變數,即建立時所處的上下文環境。

複製代碼 代碼如下:

function hello(){
    var char = "hello,world";
    function print(){
        console.log(char);
    };
    return print();
}

需要注意的是這裡的print函數引用了外部hello函數的char變數,於是在這裡我們能夠返回一個
複製代碼 代碼如下:

hello,world

而這個功能在某種意義上來說,應該是要歸功於範圍。當然了,我們沒有辦法直接存取char,除非是我們聲明這個變數的時候出錯了。如
複製代碼 代碼如下:

function hello(){
    char = "hello,world";
    function print(){
        console.log(char);
    };
    return print();
}

僅僅是因為少了個var。

複製代碼 代碼如下:

在這裡hello變成一個閉包 了。 閉包是一種特殊的對象。它由兩部分構成:函數,以及建立該函數的環境。環境由閉包建立時在範圍中的任何局部變數組成。

Javscript 閉包與this

需要注意的是讀取this與arguments時,可能是會出問題的。

複製代碼 代碼如下:

function hello(){
    this.char = "hello,world";
    function output(){
        char = "I'm no hello world";      
        console.log(this.char);
    };
    return output();
}

當然了這個例子並不夠貼切,so,我們需要一個額外的例子來解釋這個問題,下面引用一個《Javascript進階程式設計》中的一個例子,來說明這個問題。
複製代碼 代碼如下:

var name = "The window";

var object = {
    name: "My Object",

    getNameFunc: function(){
        return function(){
            return this.name;
        }
    }
};
object.getNameFunc()()


只是這種用法實在是,而解決方案便是儲存一個臨時變數that,如之前在《關於Javascript的this的一些知識》一文中所說的。

複製代碼 代碼如下:

var name = "The window";
var object = {
    name: "My Object",

    getNameFunc: function(){
        var that = this;
        return function(){
            return that.name;
        }
    }
};
object.getNameFunc()()


Javscript 閉包與讀寫變數
值得注意的是,如果我們沒有處理好我們的變數時,我們也可以修改這些變數。
複製代碼 代碼如下:

function hello(){
    var char = "hello,world";
    return{
        set: function(string){
            return char = string;
        },
        print: function(){
            console.log(char)
        }
    }
}
var say = hello();
say.set('new hello,world')
say.print() // new hello world

Javascript 閉包與效能

引用MDC的說法

複製代碼 代碼如下:

 如果不是因為某些特殊任務而需要閉包,在沒有必要的情況下,在其它函數中建立函數是不明智的,因為閉包對指令碼效能具有負面影響,包括處理速度和記憶體消耗。

文上還說到。
複製代碼 代碼如下:

 例如,在建立新的對象或者類時,方法通常應該關聯於對象的原型,而不是定義到對象的構造器中。原因是這將導致每次構造器被調用,方法都會被重新賦值一次(也就是說,為每一個對象的建立)。

聯繫我們

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