- 普通函數
function box(){
return 'Lee';
}
alert(box()); //Lee
- 匿名函數
function (){ //單獨的匿名函數是無法運行的 ,就算能運行也無法調用 因爲沒有名稱
return 'Lee';
}
- 把匿名函數賦值給變量
var box=function () {
return 'Lee';
}
alert(box()); //Lee
- 通過自我執行來執行匿名函數
(function (){
alert('Lee'); //Lee
})();
- 把匿名函數自我執行的返回值付給變量
var box=(function () {
return 'Lee';
})();
alert(box); //Lee
- 自我執行後用alert打印
alert((function () {
return 'Lee';
})());
- 自我執行匿名函數的傳參
(function (age) {
alert(age);
})(100);
函數裏面放匿名函數(形成閉包)
function box(){
return function(){ //形成閉包
return 'Lee';
}
}
alert(box()()); //Lee
//另一種返回方法
//var b=box();
//alert(b());
創建閉包的常見方式就是一個函數的創建另一個函數,通過另一個函數訪問這個函數的局部函數
function box(){
var age='100';
return function (){
return age;
}
}
alert(box()()); //100
使用全局變量進行累加
var age='100'; //全局變量
function box(){
age++
}
//alert(age) //全局 100
box();
alert(age); //101
box();
alert(age); //102
box();
alert(age); //103
使用局部變量進行累加
function box(){
var age='100';
age++
return age;
}
alert(box()); //101 不管執行多少次都是101 放在裏面每次都被初始化了
alert(box()); //101
alert(box()); //101
使用匿名函數實現變量駐留在內存中從而實現累加
function box(){
var age=100;
return function(){
age++;
return age;
}
}
var b = box();
alert(b()); //101
alert(b()); //102
alert(b()); //103
循環裏的匿名函數的取值問題
//使用較多的一種方法
function box(){
var arr=[];
for(var i=0; i<5; i++){
arr[i]=(function(num){ //通過自我即使執行匿名函數
return function(){ //因爲閉包可以將變量駐留在內存中中,和上節課的累加是一個道理
return num;
};
})(i);
}
//已經執行完畢了,num爲什麼可以0,1,2,3,4
return arr;
}
var b= box();
for(var i=0;i<5;i++){
alert(b[i]());
}
關於This對象
var box={
getThis:function (){
return this;
}
}
alert(this); //[object window]
alert(box.getThis()); //[object object]
//this的指向問題
var user='the window';
var box={
user:'The Box',
getUser:function(){
return function(){
return this.user;
};
}
}
alert(user); //the window
alert(box.getUser()()); //The window 特別注意: 閉包在運行時指向window
如何閉包裏面this指向box(方法一:使用對象冒充)
var user='the window';
var box={
user:'The Box',
getUser:function(){
return function(){
return this.user;
};
}
}
alert(box.getUser()()); //the window;
alert(box.getUser().call(box)); //the box 對象冒充
如何讓閉包裏的this指向box(方法2:改變作用域)
var user = 'the window';
var box= {
user:'the box',
getUser:function(){ //這裏的作用域是box
var that = this; //把這裏的作用域賦值給下面的作用域
}
return function(){ //這裏的作用域是Window
return that.user;
}
}
alert(box.getUser()()); //The Box