What is a closure
A closure is a [function] (a scope can access local variables of another function)
The role of closure
Extend the scope of variables
function f() {
let num = 21;
return function () {
console.log(num);
}
}
f()();
// 此时,函数f就是一个闭包(Closure)
Think about whether the example is a 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()());