function test111(){
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
return this.name;
};
}
};
alert(object.getNameFunc()()); //The Window
}
这是我在网上看的闭包的讲解,但是我自己试的时候alert根本什么都没有输出,如果我写错了,那么正确的写法是什么呢?如果按正确的方法能够输出 The Window,但是我还是觉得应该输出 My Object啊,高手给解释一下这段代码!!!
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
return name;
}
};
return object;
};
var object = test111();
object.getNameFunc();
这时候的this指向全局的~你全局没有这个变量...
不知道是不是这样..
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
return name;
},
getNameFunc1 : function(){
return this.name;
}
};
return object;
};
var object = test111();
console.log(object.getNameFunc());//The Window
console.log(object.getNameFunc1());//My Object
也是变量的使用范围
function test111(){
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
alert(this.name);
return function(){
alert(eval(this));
return this.name;
};
}
};
alert(object.getNameFunc()()); //The Window
}
test111();
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
return this.name; //这个例子的意思是:this是指向window,而不是var object.
};
}
};
alert(object.getNameFunc()()); //The Window//上面的alert这样写容易理解一点:
var f1 = object.getNameFunc();
var content =f1(); //这里f1是函数function(){ return this.name },谁调用f1,this指向谁,那就是window咯
alert(content);PS:这个作为闭包的例子,个人感觉,不是很好。
第二個name是object對象的屬性,不是window對象的,你輸出的this 是指向window對象的,你在return this.name;前面alert(this==window);
函数执行后的结果是thi.name this指向了window。而window没有这个变量!
so....
var name = "The Window";
return object = {
name : "My Object",
getNameFunc : function(){
alert(name)
}
}
})()
test111.getNameFunc()
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
return this.name;
};
}
};
alert(object.getNameFunc()()); //The Window
}
test111()
return this.name; 里的this指向window对象 相当于widnow.name ( 当前window的名称)
把var name = "The Window";
放到全局 的目的就不用我说了。
var i=0;
function b(){
alert(++i);
}
return b;
}
var c = a();
c();