闭包
闭包是指有权访问另一个函数作用域中的变量的函数。
闭包只取到包含函数中任何变量的最后一个值,如下所示:
function createFunctions() {
var result = new Array();
for(var i = 0; i< 10; i++){
result[i] = function() {
return i;
}
}
return result;
}
这个函数会返回一个函数数组,每个函数返回的都是10;可以通过创建另一个匿名函数实现函数数组返回他们的索引值:
function createFunctions() {
var result = new Array();
for(var i = 0; i< 10; i++) {
result[i] = function(num) {
return function() {
return num;
}
}(i);
}
return result;
}
关于this对象
this对象是在运行时基于函数的执行环境绑定的:在全局变量中,this等于window,当函数被作为某个对象方法调用时,this等于那个对象。然而匿名函数具有全局性,所以this对象也指向window。
var name = "The window";
var object = {
name : "My Object",
getNameFunc: function() {
return function() {
return this.name;
}
}
};
alert(object.getNameFunc()()); //The window
如果想访问object的对象,可以把this保存在闭包可以访问的变量中:
var name = "The window";
var object = {
name : "My Object",
getNameFunc: function() {
var that = this;
return function() {
return that.name;
}
}
};
有些情况下this的值会发生改变:
var name = "The window";
var object = {
name: "My Object",
getName: function() {
return this.name;
}
}
object.getName(); //"My Object"
(object.getName)(); //"My Object"
(object.getName==object.getName)() // "The window"
(object.getName==object.getName)()
这个先执行了一条赋值语句,然后调用赋值后的结果,因为这个赋值表达式的值是函数本身,所以this的值得不到维持。