javascript - YDKJS - 'this' 是如何工作的?

标签 javascript node.js this

<分区>

我从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"
})();

关于javascript - YDKJS - 'this' 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47207531/

相关文章:

javascript - jquery:如果第一个选择器返回为空,是否有一种简洁的方法可以有条件地使用第二个选择器?

node.js - “bash”不被识别为内部或外部命令

javascript - Puppeteer - 单击具有指定文本的跨度

javascript - !0 相对于 boolean true 的优势

javascript - JSON.stringify 的单行输出

node.js - 使用 AppJS 部署应用程序?

c++ - 模拟一个虚拟拷贝构造函数

javascript - 如何使用 $(this) 获取动态 DIV 中图像的 src

jquery - 包含元素的每一行,然后删除该行中的类

javascript - EXPRESS:Router.use() 需要一个中间件函数,但得到一个对象