1

I have the following object:

var car = {
  doors: 4
  wheels: 4
}

This is used in many files, is there a way that it can be checked easily across the entire codebase?

function insertCar(car) {
  if (!isCar(car)) {
    console.log('not a car')
  }
}
0

1 Answer 1

4

If I understood you correctly, instaceof will be the answer. You can do something like this:

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}
var mycar = new Car('Honda', 'Accord', 1998);
var a = mycar instanceof Car;    // returns true
var b = mycar instanceof Object; // returns true

As for exporting and importing, you need to define your object in one file and export it:

module.exports = function Car(make, model, year) {
 //...
}

Then you import it in whichever file you want with

import Car from 'components/car' 

where components/car is an example of your file where object Car is exported from, in this case Car.js which is located in directory components.

Sign up to request clarification or add additional context in comments.

3 Comments

great, thanks! Is it possible for instanceof Car to be used across files?
Read about export and import
@timothyylim I added now how you can export and import it. I hope it helps you.

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.