简体   繁体   中英

JavaScript Classes and Modules in NodeJS

I am having a hard time understanding how can I import a separate .js file into my index.js node file.

I created a file pokemon.js as shown below:

var pokemon = (function(){

  function Pokemon(name) {

    this.name = name; 
    console.log("pokemon");
  }

})();

module.exports.Pokemon = pokemon; 

And now in my index.js I want to use it:

var Pokemon = require('./models/pokemon.js');

// how do I call the Pokemon function?

UPDATE :

var Pokemon = require('./models/models.js');
var app = express();

var pokemons = [];

app.get("/pokemon/all",function(req,res){

  var pokemon = Pokemon("Pikachu"); // Pokemon is not a function



})

Here is the solution that I found:

models.js:

module.exports = function(name) {
  this.name = name; 
}

index.js: 

var Pokemon = require('./models/models.js');
var app = express();

var pokemons = [];

app.get("/pokemon/all",function(req,res){

  var pokemon = new Pokemon('Pikachu');
  pokemons.push(pokemon);
  res.json(pokemons);

})

I see you want to export the object constructor.

pokemon.js

function Pokemon(name){
   this.name = name;
   console.log(this.name);
}
// if any prototype
Pokemon.prototype.serviceOne = function(){ };
Pokemon.prototype.serviceTwo = function(){ };


module.exports = Pokemon;

index.js

var Pokemon = require('path/to/pokemon'); 
app.get("/pokemon/all",function(req,res){

    var pikachu= new Pokemon("Pikachu"); 
    pikachu.serviceOne();
    pikachu.serviceTwo();

})

the provided by @catta just have a little bug try :

var pokemon = function(name) {
this.name = name; 
console.log("pokemon");
}
module.exports.Pokemon = pokemon; 

in the index.js

var Pokemon = require('./models.js'); 
Pokemon.Pokemon('name') //output name

pokemon.js

var pokemon = function(str){
    this.name = str; 
    console.log(this.name);
};
module.exports.Pokemon = pokemon;

main.js

var Pokemon = require('./models/models.js');
var app = express();
var pokemons = [];
app.get("/pokemon/all",function(req,res){
  pokemons.push(Pokemon.Pokemon("Pikachu"));
})

When you set var key to require it just references to that file. Therefore you need "Pokemon.Pokemon()"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM