I am trying my might at doing a NODE JS project, and learning the in's and outs of the Node JS structure. I have looked all over the internet to find out how to do this with little or no luck. The problem is as follows:
I have a class called player, which was created in a file called player.js
var playa = function ()
{
this.createPlayer = function(){
}
}
In my index.js file I link my player
var playa = require("./player.js");
however, when I try to reference my player
io.on('connection', function(socket){
var player = new playa();
player.createPlayer();
});
the console tells me that playa is not a function and the server stops.
2.If it is possible too structure my objects this way, how do I link them/reference them correctly?
If you export the constructor as a property of module.exports
, then you'll have to refer to it by that as a property of the value returned from require()
:
var playa = require("./player.js");
var player = new playa.playa();
If you want require()
to return the function itself, you can write
module.exports = function()
{
this.createPlayer = function(){
}
}
Add this to the bottom of your player.js file
module.exports.playa = playa;
This will allow that "class" to be available
EDIT
You will need to create an instance like the following:
var p = require('./player.js')
var player = new p.playa();