1

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)

  • 1
    [Use modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) and `export` the class / `import` it before usage. See [Using Node.js require vs. ES6 import/export](https://stackoverflow.com/q/31354559/4642212). – Sebastian Simon Mar 13 '22 at 07:08

2 Answers2

1

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

Samson
  • 1,336
  • 2
  • 13
  • 28
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 :)