【发布时间】:2021-08-04 00:11:01
【问题描述】:
我正在做一个关于 Javascript 的 Salesforce Trailhead,并提出了一个关于这个范围的问题。
我认为 this.hello 在函数内部是未定义的,因为 this 将指向窗口,其中 .name down 不存在。但是 window == this 是错误的,并且该对象的日志显示它访问了属性。
那么为什么 this.name 未定义?
let message = {
hello: "Hello",
names: ["Sue", "Joe"],
showMessage: function () {
console.log("this, message");
console.log(window == this);
console.log(this);
this.names.forEach(function (name) {
console.log(this.hello + " " + name);
});
}
};
message.showMessage();
/*
false
Object
hello: "Hello"
names: (2) ["Sue", "Joe"]
Sue
"undefined Sue"
"undefined Joe"
*/
返回:
【问题讨论】:
-
因为您使用的是对象原语而不是类实例?如果你需要一个行为 OOP(ish) 的
this,然后编写一个类,创建它的一个实例,你就完成了。否则,JS 的作用域规则很特别,你应该deeply familiarise yourself with howthisscoping works。 -
每个
function() {}都有自己的this,因为您在forEach中的功能与showMessagefunction不同,它们都有自己不同的this。在你的 forEach 回调中记录this,你会看到window
标签: javascript scope this