定义:
能够访问其他函数内部变量的函数,被称为闭包。闭包让你可以在一个内层函数中访问到其外层函数的作用域
应用场景
单例模式
单例模式是一种常见的设计模式,它保证了一个类只有一个实例。
function Singleton() {
this.data = 'singleton';
}
Singleton.getInstance = (function() {
var instance;
return function() {
if (instance) {
return instance;
} else {
instance = new Singleton();
return instance;
}
}
})();
const a = Singleton.getInstance();
const b = Singleton.getInstance();
console.log(a===b); // true
模拟私有属性与方法
javascript 没有 java 中那种 public、private 的访问权限控制,对象中的所用方法和属性均可以访问,这就造成了安全隐患,内部的属性任何开发者都可以随意修改。虽然语言层面不支持私有属性的创建,但是可以用闭包的手段来模拟出私有属性:
var Counter = (function() {
var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(1);
},
decrement: function() {
changeBy(-1);
},
value: function() {
return privateCounter;
}
}
})();
console.log(Counter.value()); /* logs 0 */
Counter.increment();
Counter.increment();
console.log(Counter.value()); /* logs 2 */
Counter.decrement();
console.log(Counter.value()); /* logs 1 */
循环赋值
for(var i = 0; i < 5; i++){
(function(j){
setTimeout(function(){
console.log(j)
}, 1000)
})(i)
}
// 使用let,块级作用域
for(let i = 0; i < 5; i++){
setTimeout(function(){
console.log(i)
}, 1000)
}
使用闭包应该注意什么
容易导致内存泄漏。闭包会携带包含其它的函数作用域,因此会比其他函数占用更多的内存。过度使用闭包会导致内存占用过多,所以要谨慎使用闭包。
例如,在创建新的对象或者类时,方法通常应该关联于对象的原型,而不是定义到对象的构造器中。原因是这将导致每次构造器被调用时,方法都会被重新赋值一次(也就是说,对于每个对象的创建,方法都会被重新赋值)。
function MyObject(name, message) {
this.name = name.toString();
this.message = message.toString();
this.getName = function() {
return this.name;
};
this.getMessage = function() {
return this.message;
};
}
在上面的代码中,我们并没有利用到闭包的好处,因此可以避免使用闭包。修改成如下:
function MyObject(name, message) {
this.name = name.toString();
this.message = message.toString();
}
MyObject.prototype.getName = function() {
return this.name;
};
MyObject.prototype.getMessage = function() {
return this.message;
};
this