Closures are functions that refer to independent (free) variables (variables that are used locally, but defined in an enclosing scope). In other words, these functions 'remember' the environment in which they were created. --- MDN
看不懂上面的英文這么辦,下面是中文翻譯
閉包是指那些能夠訪問獨立(自由)變量的函數(shù) (變量在本地使用,但定義在一個封閉的作用域中)。換句話說,這些函數(shù)可以“記憶”它被創(chuàng)建時候的環(huán)境。
關(guān)于閉包已經(jīng)有很多很多的文章了,文章的最后會放一些鏈接,在這里我只寫以下幾點
- 閉包的實現(xiàn)是因為Js中有函數(shù)作用域,變量查詢是一級一級查詢上去,直到根作用域也就是說在任何一級的作用域中都可以訪問之前所有作用域連的變量,同時內(nèi)存回收機制是不會回收還被引用的變量。
- 閉包不是實現(xiàn)Js類的基礎(chǔ),但是可以通過閉包實現(xiàn)類的私有變量和私有函數(shù)
- 閉包的性能很差,有時候可以綁定在prototype中(只可以訪問this下的變量)
//在這個例子中firstName和LastName不想直接被外界訪問,同時可以使用閉包使外界獲取到值,
//同時函數(shù)盡量綁定在prototype上,所以getFullName綁定在prototype上,
//所以我個人認為在這樣的情況下,一些用于訪問私有變量的基礎(chǔ)函數(shù)可以使用閉包,
//大多數(shù)類函數(shù)可以綁定在prototype中,通過可以訪問私有變量的基礎(chǔ)函數(shù)來實現(xiàn)訪問私有變量
var Man = function(){
var firstName = 'wang';
var LastName = 'yuekai';
this.getFirstName = function(){
return firstName;
}
this.getLastName = function(){
return LastName;
}
}
Man.prototype.getFullName = function(){
return this.getFirstName() + this.getLastName()
}