In JavaScript, there are 2 scopes, divided into global scopes, and function scopes,
On the browser side, the global scope is the property of the Window object.
The function scope is the property of the object generated by a function;
<! DOCTYPE html>
The above is the result of the code running, when using this, pay special attention, because this is at runtime, the dynamic binding of an object, there are many uncertainties, may produce unexpected results.
in Nodejs, there are also 2 scopes, divided into global scope, and module scope, As we explore, save the following as Test1.js, run
var name = ' Var-name '; name = ' name '; global.name= ' global-name '; this.name = ' module-name '; Console.log (global.name); Console.log (this.name); Console.log (name);
We see var name = ' Var-name '; name = ' name ';is a defined local variable;and Global.name= ' global-name '; is to define a name property for the global object,
and this.name = ' module-name '; is to define a Name property for the module object
So let's verify, save the following as Test2.js, run
var T1 = require ('./test1 '); Console.log (t1.name); Console.log (Global.name);
As we can see from the results, we successfully imported the Test1 module and ran the Test1 code because global.name was output in Test2,
The t1.name is defined by THIS.name in the Test1 module, which indicates that this is a module-scoped object.
Well, let 's talk about CommonJS, and then the next guess,
According to the COMMONJS specification, a single file is a module. The load module uses the Require method, which reads a file and executes it, and finally returns the exports object inside the file.
So let's take a look at the node module exports, Module.exports, this
Console.log (Module.exports = = = this); Console.log (Module.exports = = = exports); Console.log (this = = = exports);
As you can see from the above code execution, they all point to the same object,So what's the difference, why it's so designed, what's good,
We analyze later, please continue to pay attention to ...