Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda