閉包的描述:閉包就是能夠讀取其他函數(shù)內(nèi)部的變量的函數(shù)妄辩。
閉包的用途:1、讀取函數(shù)內(nèi)部的變量山上。2眼耀、讓變量的值一直保持在內(nèi)存中。
閉包的注意點(diǎn):1佩憾、閉包會讓函數(shù)的變量保存在內(nèi)存中哮伟,內(nèi)存消耗很大。所以不能濫用閉包妄帘。(退出前將局部變量全部刪除)2楞黄、閉包可以改變父函數(shù)內(nèi)部的值
理論要通過實(shí)踐去理解。
案例1
var name = "The Window";
var object = {
name: "My Object",
/*console.log(this)
* 這時(shí)候的this將是object這個(gè)對象:{ name: 'My Object', getNameFunc: [Function: getNameFunc] }*/
getNameFunc: function () {
/*這時(shí)候console.log(this)
*this將是object這個(gè)對象:{ name: 'My Object', getNameFunc: [Function: getNameFunc] }*/
return function () {
/*在匿名函數(shù)中console.log(this)抡驼,匿名函數(shù)本身也是個(gè)閉包鬼廓,這時(shí)候的this指向window
* 輸出是成片的這個(gè):
* { console: [Getter],
DTRACE_NET_SERVER_CONNECTION: [Function],
DTRACE_NET_STREAM_END: [Function],
DTRACE_HTTP_SERVER_REQUEST: [Function],
DTRACE_HTTP_SERVER_RESPONSE: [Function],
DTRACE_HTTP_CLIENT_REQUEST: [Function],
DTRACE_HTTP_CLIENT_RESPONSE: [Function],
global: [Circular],
process:
process {
title: '/usr/local/bin/node',
等等...
*/
console.log(this)
return this.name;
/* 返回this.name,全局this里根本沒定義name啊。所以返回undefined*/
};
}
};
console.log(object.getNameFunc()());
如果想讓他有輸出致盟,就全局定義object
object = {
name : "My Object",
getNameFunc : function(){
var that = this;
return function(){
return that.name;
};
}
再來個(gè)案例
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
/*這時(shí)候的this碎税,就是指向object這個(gè)對象柏副,將其復(fù)制給that,目的為了給下面的匿名函數(shù)使用*/
var that = this;
return function(){
return that.name;
};
}
};
alert(object.getNameFunc()());