简体   繁体   English

NodeJS中的JavaScript类和模块

[英]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. 我很难理解如何将单独的.js文件导入到index.js节点文件中。

I created a file pokemon.js as shown below: 我创建了一个文件pokemon.js,如下所示:

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: 现在在我的index.js中,我想使用它:

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

// how do I call the Pokemon function? //如何调用Pokemon函数?

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: 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 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 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 : @catta提供的只是有一个小错误尝试:

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

in the index.js 在index.js中

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

pokemon.js pokemon.js

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

main.js 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. 当您将var key设置为要求时,仅引用该文件。 Therefore you need "Pokemon.Pokemon()" 因此,您需要“ Pokemon.Pokemon()”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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