console.log("0");
var name = "The Window";
console.log("1");
var object = {
name: "My Object",
getNameFunc: function () {
return function () {
console.log(this.name);
return this.name;
};
}
};
console.log("3");
console.log(object.getNameFunc()());
}
这是原代码地址:https://www.w3cschool.cn/jsnote/jsnote-closure.html
下面是我自己运行的代码
function JSPfunction003() {
console.log("0");
var name = "The Window";
console.log("1");
var object = {
name: "My Object",
getNameFunc: function () {
return function () {
console.log(this.name);
return this.name;
};
}
};
console.log("3");
console.log(object.getNameFunc()());
}
另外一种this容易被用错的情况是使用闭包。一定要记住,闭包使用this关键词无法访问外部函数的this变量。函数的this变量只能被自身访问,其内部变量不行
所以是undefined,没有输出
var name = "The Window";要放到全局环境中,做为全局变量才行。
全局变量会被系统认做是window对象的属性。你把var name = "The Window";放到函数中就成局部变量了。
或者改成 window.name = "The Window"; 也可以。
我按照你这个打印出来怎么有结果?