Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
Do parameters sent to a JavaScript module constructor require special handling?

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!