Node.js: this, module.exports, and the wrapping function

Node.js: this, module.exports, and the wrapping function
0.0 0

#1

Hello,

Looking for some confirmation/clarification on what this means within a NodeJS module. Just writing a simple one for one of the projects…

exports.functionA = functionA () {
    // do many things
}

exports.functionB = functionB () {
   let result = this.functionA
   // do more things
}

Why or how does this.functionA work? I’ve read the MDN article on this and the idea is that if this isn’t defined it will be set to the Global object. Is that what’s happening in this node module?


#2

this is a special keyword created by the Javascript Engine for every Execution Context .

Running a javascript program creates a Global Execution Context (wrapper for the code)

So when this Global Execution Context is created the this keyword refers to the top level scope in the program . i.e.
the window in the browser and in Node.js - the module itself via which the this keyword is called upon.

As every variable and function declared in the global scope is attached to the global object (window in case of browser) and since this refers to the global object therefore this.functionA means attach the functionA to the global object. But that is not necessary as the global functions and variables are automatically attached to global object…

I know its a little hard to grasp topic … if you have any further questions feel free to ask … You can also have a look at youtube videos for that matter.


#3

Thanks vikrant17.

Here is the interesting part. In my module, calling functionA from functionB didn’t work. I get an undefined error.

It only worked once I used this.functionA from within functionB


#4

Ok I see it.

This is because you have created a function and attached to the exports object directly.

So the global object does not have functionA to run (since functionA is a method of exports)
so calling functionA means you are calling a function
attached to the global object which infact does not exist…

But in case of the functionB,
since it is also defined as a method of exports object, the this variable inside the functionB refers to the object it is attached to (here, the exports). (if a function is attached to an object then the this keyword refers to the object and this function is called a method).
Therefore this.functionA() corresponds to exports.functionA() inside the functionB .

And functionA() will give you error since there is no such function in the global object.

Hope that makes sense.


#5

Thanks!

Your explanation made a lot of sense. I see the connection now. :tada:

Now I can sleep… Haha


#6

I am glad I could help you. :slight_smile: