Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

353
Views
How to call a class in another node.js file

I have 2 files. One is car.js

class Car {
  constructor(owner){
    this.owner = owner;
  }
  drive(){
    console.log("Vroom Vroom");
  }
}

The other is race.js from where I want to create a Car object. I tried:

car1 = new Car("Rick Astley");
car1.drive();

But I keep getting the error that

ReferenceError: Car is not defined

What changes should I make to my code ?

(Both files are in the same directory)

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

First you need to export Car from the first file. There are multiple ways to do this, for example you could do

export default class Car{
  // Your code here
}

Then in your second file, you have to import the Car object:

import Car from ./car;

car1 = new Car("Rick Astley");
car1.drive();

about 4 years ago · Juan Pablo Isaza Report

0

Thanks to Sebastian Simon for the solution in the comments. I just thought I'll make it a formal answer.

Change car.js to

class Car {
  constructor(owner){
    this.owner = owner;
  }
  drive(){
    console.log("Vroom Vroom");
  }
}
module.exports = Car;  // Added this

and race.js to

const Car = require('./Car.js')  // Added this
car1 = new Car("Rick Astley");
car1.drive();

Thanks again to everyone for their help :)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!