日期:2014-05-16 浏览次数:20489 次
function test111(){
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
return this.name;
};
}
};
alert(object.getNameFunc()()); //The Window
}
var name = "The Window"; //等效于:window.name="The Window"
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);
------解决方案--------------------
第一個name是一個局部變量,不是window對象的屬性,別搞錯了。
第二個name是object對象的屬性,不是window對象的,你輸出的this 是指向window對象的,你在return this.name;前面alert(this==window);
------解决方案--------------------
var name = "The Window";
function test111(){
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
return this.name;
};
}
};
alert(object.getNameFunc()()); //The Window
}
test111()
------解决方案--------------------
一个简单的js闭包:
function a(){
var i=0;
function b(){
alert(++i);
}
return b;
}
var c = a();
c();