2

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?

Phil
  • 348
  • 1
  • 15
  • 2
    Usually you would define `display` on `TestModule.prototype`, so that you don't end up creating multiple function objects for each instance that do the same thing. When it's defined on the prototype, you don't have access to the `param` variable from the surrounding scope, so `this.param` is needed – Nick Parsons Mar 15 '22 at 00:10
  • You’re essentially asking what the difference between variables and properties is. See [What is the difference between javascript property and javascript variable?](/q/26421417/4642212). – Sebastian Simon Mar 15 '22 at 00:10
  • JS supports actual classes now, I recommend learning that instead of using functions as classes. –  Mar 15 '22 at 00:11
  • @ChrisG It's still recommended to learn that classes are functions with a `.prototype` property, no matter what syntax is used to create them. – Bergi Mar 15 '22 at 00:38

2 Answers2

1

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.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
0
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

Lebster
  • 289
  • 5
  • 12