標籤: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 匿名函數和閉包