所谓的闭包应该是指: 内部函数读取当前函数以外的变量,即创建时所处的上下文环境。
function hello(){
var char = "hello,world";
function print(){
console.log(char);
};
return print();
}
hello,world
function hello(){
char = "hello,world";
function print(){
console.log(char);
};
return print();
}
在这里hello变成一个闭包 了。 闭包是一种特殊的对象。它由两部分构成:函数,以及创建该函数的环境。环境由闭包创建时在作用域中的任何局部变量组成。
Javscript 闭包与this
需要注意的是读取this与arguments时,可能是会出问题的。
function hello(){
this.char = "hello,world";
function output(){
char = "I'm no hello world";
console.log(this.char);
};
return output();
}
var name = "The window";var object = { name: "My Object",
getNameFunc: function(){ return function(){ return this.name; } } }; object.getNameFunc()()
var name = "The window";
var object = {
name: "My Object",
getNameFunc: function(){
var that = this;
return function(){
return that.name;
}
}
};
object.getNameFunc()()
function hello(){
var char = "hello,world";
return{
set: function(string){
return char = string;
},
print: function(){
console.log(char)
}
}
}
var say = hello();
say.set('new hello,world')
say.print() // new hello world
引用MDC的说法
如果不是因为某些特殊任务而需要闭包,在没有必要的情况下,在其它函数中创建函数是不明智的,因为闭包对脚本性能具有负面影响,包括处理速度和内存消耗。
例如,在创建新的对象或者类时,方法通常应该关联于对象的原型,而不是定义到对象的构造器中。原因是这将导致每次构造器被调用,方法都会被重新赋值一次(也就是说,为每一个对象的创建)。