简体   繁体   中英

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

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

Outputs

VS Code:

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).

In Node.js, This is not the case. NodeJs has something called global object.

Here are some facts:

  • In the Node.js module system, each file is treated as a separate module.
  • 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.

NodeJs: 在 NodeJs 上

Browser: 在浏览器上

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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