type of an object

Posted on
  • How do I detect type of an object ?
    For example var x = new SPI()
    X returns SPI: { }, so in web IDE(only in web IDE) I see its an SPI object
    typeof x returns ="object"
    Is there any JS command, something like objectType, which returns "SPI"

  • If you know what type you expect, you can use instanceOf. For example:

    if (!(serialPort instanceof Serial)) {throw '"serialPort" parameter is not a serial port!'}
    if (!(rxPin instanceof Pin)) {throw '"rx" parameter is not a Pin!';}
  • As far as I know there's nothing built-in, since the name of the object isn't actually stored in the object itself in Espruino.

    However if the class is something that's defined in the global scope, like SPI, then you can do:

    >x = new SPI()
    =SPI: {  }

    But if you know what you're looking for, you're far better off going with @AkosLukacs's suggestion as it's far faster and neater!

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview

type of an object

Posted by Avatar for JumJum @JumJum