简体   繁体   English

在javascript中检查自定义对象的类型

[英]Type checking a custom object in javascript

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')
  }
}

If I understood you correctly, instaceof will be the answer. 如果我对您的理解正确, 那么instaceof就是答案。 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 . 其中, components/car是文件的示例,对象Car是从中导出的,在本例中为Car.js ,位于目录components

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM