首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

求指导一个关于闭包的有关问题

2013-10-22 
求指导一个关于闭包的问题var name the windowvar object function (){this.name My objectth

求指导一个关于闭包的问题
var name = "the window";
var object = function (){
        this.name = "My object";
this.getNameFunc = function(){
return function (){
alert(this.name);
return this.name;
};
}
};

var aa = new object();
alert(aa.getNameFunc()());

我得倒的结果是两条the window,请问这内在原理是怎么回事啊,新手。  JS闭包
[解决办法]


var name = "the window";
var object = function (){
    this.name = "My object";
    this.getNameFunc = function(){
        return function (){
            alert(this.name);
            return this.name;
        };
    }
};

var aa = new object();
var bb = aa.getNameFunc();
//getNameFunc返回的是一个匿名function,也就是说:
bb = function (){
   alert(this.name);
   return this.name;
};
var cc = bb();
//这时,bb内部的this为window,因此alert的是window.name
//window.name被第一句var name给覆盖了,所以是"the window"
alert(cc);//alert(window.name);

热点排行