NodeJS中的JavaScript类和模块

时间:2017-03-20 02:38:49

标签: javascript node.js

我很难理解如何将单独的.js文件导入到我的index.js节点文件中。

我创建了一个文件pokemon.js,如下所示:

var pokemon = (function(){

  function Pokemon(name) {

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

})();

module.exports.Pokemon = pokemon; 

现在我的index.js中我想用它:

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

//如何调用口袋妖怪功能?

更新

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



})

以下是我找到的解决方案:

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);

})

3 个答案:

答案 0 :(得分:1)

我看到你要导出对象构造函数。

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();

})

答案 1 :(得分:0)

由@catta提供的只是有一点bug试试:

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

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

答案 2 :(得分:0)

<强> 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"));
})

设置var key时,只需要引用该文件即可。因此你需要“Pokemon.Pokemon()”