闭包是什么
闭包是一个【函数】(一个作用域可以访问另一个函数的局部变量)
闭包的作用
延伸变量的作用域
function f() {
let num = 21;
return function () {
console.log(num);
}
}
f()();
// 此时,函数f就是一个闭包(Closure)
思考一下例子是不是闭包
window.name = 'window';
let obj = {
name: 'obj',
getName: function () {
let that = this;
return function () {
return that.name;
}
}
}
console.log(obj.getName()());
window.name = 'window';
let obj = {
name: 'obj',
getName: function () {
return function () {
return this.name;
}
}
}
console.log(obj.getName()());