0

I really have no idea how Javascript works. I am used to OOP languages. I have two javascript files, and I want to make a person object. I'm running Main.js as a node file.

Main.js

var p = require('./Person.js')
var person = new Person();

Person.js

exports = function Person ()
{
    console.log("hello")
}

I've tried many different things, but it always says Person is not defined.

node Main

ReferenceError: Person is not defined.

4
  • 1
    You're importing the Person code's exports as the value of variable p, so it should be var person = new p(); Commented Dec 27, 2015 at 19:33
  • After implementing your suggestions I still have the error "TypeError: Person is not a function" at require line. Commented Dec 28, 2015 at 17:29
  • Does Person.js really look exactly like what you've posted here? Commented Dec 28, 2015 at 17:33
  • Oh wait a sec - it should be module.exports = ... not just exports. (I think.) Commented Dec 28, 2015 at 17:36

2 Answers 2

3

Your issue lies within these lines of code:

var p = require('./Person.js');
var person = new Person();

p holds the module from Person.js, so you should create your new Person like so:

var person = new p();

Or (what I recommend for the sake of clarity) change p to Person:

var Person = require('./Person.js');
var myPerson = new Person();

Also make sure you use module.exports instead of just exports here:

module.exports = function Person ()
{
    console.log("hello")
}
Sign up to request clarification or add additional context in comments.

5 Comments

After implementing your suggestions I still have the error "TypeError: Person is not a function" at require line.
@Jim The path to your person file might be incorrect - have you checked that?
All files are in the same folder.
@Jim instead of exports = function Person () ... try module.exports = function Person () ...
@Jim glad I could help!
1

What you mean to do is probably

var Person = require('./Person.js');
var person = new Person();

1 Comment

After implementing this suggestion I still get the error "TypeError: Person is not a function" at require line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.