我从YDKJS复制了代码并且作者预期输出是“oops global”,但是当我在 Node 中运行它时,我得到“undefined”。为什么?
function foo() {
console.log(this.a);
}
var obj = {
a: 2,
foo: foo
};
var bar = obj.foo; // function reference/alias!
var a = "oops, global"; // `a` also property on global object
bar(); // "oops, global"
当您以正常方式在 Node 中运行代码时:
node implicitLost.js
...Node runs your code as a module, not at global scope. The code shown there only outputs "oops, global" if it's run at global scope (for instance, in <script>...</script>
in a browser). (Node also does this when you require(...)
your code from another script.)
You can run your code at global scope by piping it into node
instead of supplying it as an argument, using Node's REPL (note the <
redirection):
node < implicitLost.js
Why it matters:
When run in a module, since the var a = "oops, globals";
is at module scope, it's only defined within that module; it doesn't become a global. So this.a
in foo
, which is trying to access a
on the global object, doesn't see it.
Here's that code running at global scope:
function foo() {
console.log(this.a);
}
var obj = {
a: 2,
foo: foo
};
var bar = obj.foo; // function reference/alias!
var a = "oops, global"; // `a` also property on global object
bar(); // "oops, global"
这里它在一个模糊地环境中运行,就像一个 Node 在其中运行它:
(function() {
function foo() {
console.log(this.a);
}
var obj = {
a: 2,
foo: foo
};
var bar = obj.foo; // function reference/alias!
var a = "oops, global"; // `a` also property on global object
bar(); // "oops, global"
})();