I have a javascript module that looks like this:
var TestModule = function(param) {
this.display = function() {
console.log(`testModule.display called, with parameter: ${param}`);
}
}
module.exports = TestModule;
I also have a program that uses this module, like so:
var TestModule = require('./test-module.js');
var testModule = new TestModule('asdf');
testModule.display();
When I run the program, I get the following output:
testModule.display called, with parameter: asdf
All of this seems to be fine so far, and doing what I want: making the value I send in available to functions within the module.
However, I have also seen the following done in module code:
var TestModule = function(param) {
this.param = param;
this.display = function() {
console.log(`testModule.display called, with parameter: ${this.param}`);
}
}
module.exports = TestModule;
Running this second version gives me the same output as the first.
My question is, what is the purpose of this.param = param? What does that do for me that my original version does not?
The main difference is that the object returned by the constructor has the property attached to its prototype.
In the second version, console.log(testModule.param) gives "asdf" and the first version gives this property as undefined.
If you attach functions to the prototype, which is the normal approach because it only defines each function once, these functions' closures won't see param if it's not been attached to this as the second version does.
The module.exports has no bearing on this, by the way.
this.param = param
Will store the argument on the object itself, allowing you to do testModule.param and access it (like how you do testModule.display() to access the display method)
Additionally, you should use the ES6 Class Syntax to modernise your code