闭包的含义:是一个函数,可以调用其他函数声明的变量,其作用是:延长变量的使用范围
var name = "the window";
var object = {
name: "my object",
getNameFunc: function() {
return function() {
return this.name
}
}
};
console.log(object.getNameFunc()()) // 输出 the window, 其中this指向window 不存在闭包
其中 object.getNameFunc()() 可拆解成以下代码:
var f = object.getNameFunc() // 此时的this还指向object
f = function() { // 此时this已经指向window了
return this.name
}
f()
因此,输出 the window。
若改为下述代码:
var name = "the window";
var object = {
name: "my object",
getNameFunc: function() {
var that = this // 此时的this指向object
return function() {
return that.name // 此时的that指向的也为object
}
}
};
console.log(object.getNameFunc()()) // 输出 my object, 其中this指向object 存在闭包
其中 object.getNameFunc()() 可拆解成以下代码:
var f = object.getNameFunc() // 此时的this指向object
f = function() { // 此时的that指向的也为object
return that.name
}
f()