我写了一段代码,但我不明白为什么它会打印未定义
。
我期待看到“oops,global”,因为对 foo 的调用不是来自对象,所以它必须来自全局范围,这意味着 this
引用全局这个
。
我哪里错了?
var obj1 = {
a123: 2,
foo: function() {
// console.log(this); obj1 is not in this. why?
console.log(this.a123);
}
};
var a123 = "oops, global";
var f = obj1.foo;
f(); // prints undefined. why? should have printed "oops, global"
我正在使用 nodejs
在 IntelliJ 中运行代码。
最佳答案
因为在 Node js 中,如果您在外部范围内,这意味着 module.export 。在浏览器中这意味着窗口。这就是区别。
关于javascript - JS 中的这种操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51178112/