简体   繁体   English

相同的代码,但 VS Code 和浏览器控制台的“this”的 output 不同

[英]Same code but different output of 'this' for VS Code and browser console

I have executed the following code both in VS Code and browser console我在 VS Code 和浏览器控制台中都执行了以下代码

 var message = 'I am your teacher' function executeWorkshop(greeting){ return function ask(){ console.log(`${greeting}, ${this.message}`); } } executeWorkshop("Hi")();

Outputs产出

VS Code: VS代码:

Hi, undefined

Browser:浏览器:

Hi, I am your teacher

For web browsers, we have a window object. It provides the browser window functionality and also plays the role of a global object. When scripts create global variables in the web browsers, they're created as members of the global object(window object).对于web浏览器,我们有一个window object。它提供了浏览器window的功能,同时也起到了全局object的作用。当脚本在web浏览器中创建全局变量时,它们被创建为global(object)window的成员.

In Node.js, This is not the case.在Node.js,不是这样的。 NodeJs has something called global object. NodeJs 有一个叫做global object 的东西。

Here are some facts:以下是一些事实:

  • In the Node.js module system, each file is treated as a separate module.在 Node.js 模块系统中,每个文件都被视为一个单独的模块。
  • The Global objects are available in all modules.全局对象在所有模块中都可用。
  • While in browsers, the global scope is the window object, in nodeJS, the global scope of a module is the module itself, so when you define a variable in the global scope of your Node.js module, it will be local to this module.在浏览器中,全局 scope 是 window object,在 nodeJS 中,模块的全局 scope 是模块本身,因此当您在 Node.js 的全局 scope 中定义变量时,它将是该模块的本地变量。

NodeJs:节点: 在 NodeJs 上

Browser:浏览器: 在浏览器上

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM