Drahcir
Drahcir

Reputation: 11972

Create new type, or check type?

For example, I have the below constructor:

function MyType(){

    this.someProp = 'someText';

};

I create a new instance:

var myVar = new MyType();

Now I want to check the type of this object...

console.log(typeof(myVar));    //object
console.log(myVar.toString()); //[object Object]

Is there any way for typeof or the default toString method to return MyType, instead of just object.

Upvotes: 0

Views: 72

Answers (2)

DaveB
DaveB

Reputation: 9530

No, there are no custom types in Javascript. There are 9 native constructors:

  • Number()
  • String()
  • Boolean()
  • Object()
  • Array()
  • Function()
  • Date()
  • RegExp()
  • Error()

There are also 3 primitive types:

  • string
  • number
  • Boolean

Upvotes: 1

James Allardice
James Allardice

Reputation: 166031

No, you cannot override the behaviour of typeof. It's defined in the spec and there are a set number of possible return values. It uses the "type" of the operand, which can only be one of null, undefined, string, boolean, number and object.

However, instanceof should work:

console.log(myVar instanceof MyType); // true

Side note... typeof is an operator, not a function, so you don't need the parentheses around it.

Upvotes: 2

Related Questions