JavaScript 匿名函數和閉包

來源:互聯網
上載者:User

標籤:java   cal   call   變數   不同   垃圾   script   最大   getname   

// 1 匿名函數的定義與使用// 1.1 把匿名函數賦值給變數 通過變數執行var box = function() {    return "Lee";}box(); // "Lee"// 1.2 通過自我執行來執行匿名函數// (匿名函數)();(function() {    return "Lee";})(); // "Lee"// 1.3 匿名函數自我傳參(function(age) {    return age;})(100); // 100// 2 閉包// 2.1 閉包函數function box() {    return function() {        return 10;    }}box(); // 見下/*function (){    return 10;}*/box()(); // 10// 2.2 通過閉包返回局部變數function box() {    var age = 100;    return function() {        return age;    };}box(); // 見下/*function (){    return age;}*/box()(); // 100// 2.3 使用匿名函數實現局部變數駐留記憶體中從而累加function box() {    var age = 100;    return function() {        age++;        return age;    }}var b = box();b(); // 101b(); // 102b(); // 103// 銷毀引用 等待垃圾收集器來清理b = null;// 2.4 關於閉包的this對象// window是js裡最大的全域對象// this在不同的範圍所指對象不同但指向的都是對象本身// this指window對象this; // Window {...}this.name = "window";var box = {    name: "box",    getName: function() {        return function() {            // 閉包函數內 this指window對象            return this.name;        }    }}box.getName()(); // "window"// 對象冒充box.getName().call(box) // "box"var box = {    name: "box",    getName: function() {        // 閉包函數外 this指box對象        var that = this;        return function() {            return that.name;        }    }}box.getName()(); // "box"

 

JavaScript 匿名函數和閉包

聯繫我們

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