https://www.cnblogs.com/heyushuo/p/9975911.html
代码片段一。
var name = “The Window”;
var object = {
name : “My Object”,
getNameFunc : function(){
return function(){
return this.name;
};
}
};
alert(object.getNameFunc()());
代码片段二。
var name = “The Window”;
var object = {
name : “My Object”,
getNameFunc : function(){
var that = this;
return function(){
return that.name;
};
}
};
alert(object.getNameFunc()());
一是the window
二是my object
本文通过两个JavaScript代码片段展示了闭包的使用方式及其对‘this’关键字的影响。第一个例子中‘this’指向全局对象导致输出非预期结果;第二个例子通过保存‘this’到变量‘that’来确保函数内部正确引用对象属性。
280

被折叠的 条评论
为什么被折叠?



