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