Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

352
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda