The following content is all about this in nodejs rather than this in javascript. This in nodejs is different from this in javascript in the browser.
this
in globalconsole.log(this); {} this.num = 10; console.log(this.num); 10 console.log(global.num); undefined
This in the global world is an empty object by default. And in the global this has no relationship with the global object, so who exactly does this in the global point to? We will explain this in the second half of this chapter.
this
in a functionfunction fn(){ this.num = 10; } fn(); console.log(this); {} console.log(this.num); undefined console.log(global.num); 10
This in the function points to the global object, which is not the same object as this in the global. Simply put, the variable you define through this in the function is equivalent to adding an attribute to global. At this time, it is the same as global. The "this" in "has nothing to do with it".
If you don’t believe it, look at the code below to prove it.
function fn(){ function fn2(){ this.age = 18; } fn2(); console.log(this); global console.log(this.age); 18 console.log(global.age); 18 } fn();
Right, in the function this points to global.
this
in the constructorfunction Fn(){ this.num = 998; } var fn = new Fn(); console.log(fn.num); 998 console.log(global.num); undefined
In the constructor, this points to its instance, not global.
We can now talk about this in the global context. Speaking of this in the global context, it actually has something to do with the scope in Nodejs. If you want to know more about the scope in Nodejs, you can read the discussion about scope in Nodejs. Scope issue. this article.
Back to the topic, this in the global context points to module.exports.
this.num = 10; console.log(module.exports); {num:10} console.log(module.exports.num);
Why does this point to module.exports in the global view? Then you need to know more about module.exports first. For the time being, we will know this first. We will talk about module if we have the opportunity later