preface

Those of you who have studied JavaScript are no doubt aware of the orientation of this in different contexts. So look at the following code

var type = 1
function toWhere(){
	this.type = 2;
}
toWhere();
console.log(type)
Copy the code

You might think,

Here we declare a global variable type, which is assigned to 1 when type=1 is executed. This refers to the window. This. type=2, and the global variable type is set to 2. Finally, we print the global variable type which is obviously 2.Open up your browser and verify that there’s no problem. There’s a bright 2 there.

So is this the end of it?

If you have learned node, re-execute the above code with NodeJS and you will see the difference.Now you see why that one is so wrong, isn’t it equal to 2?

The relevant debugging

As you can see from the example above, the same JS code running in a browser is not the same as running in nodeJS.

This is actually because this points to the problem, but the point is not the same as what we usually know about the point. This pointing problem is due to how Node works

Var type = 1 function toWhere() {this.type = 2 console.log(" this points to ",this)} toWhere() console.log(type) Console. log(" global this",this)Copy the code
  1. Print this in the browser

Function this refers to window, and global this refers to window

  1. Prints this in nodeJs

There you go. Function this refers to Object [global].

When we assign a value to this, it actually attaches to the global object. So it doesn’t change the value of this globally

Principle analysis of Node

So why is that

First we need to understand how nodeJs works

A script file executed by the browser directly at the global scope

In Node, which hides code in an anonymous function that is called immediately, you can use global to access the global scope

In the previous explanation, we saw that a this was printed externally to refer to an empty object {}, but any file running in Node is actually wrapped in a {}, so script files are executed in their own closure, similar to the following

{(function(){// script file})()}Copy the code

In the previous example, outside the function this points to an empty object {}, while inside the function this has no specified execution context, so it points to the global object – (which can access the global scope of the anonymous function execution context).