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.
-
The above has been tested in Chrome console.
-
JSFiddle: http://jsfiddle.net/keqHN/
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,
instanceofshould work:Side note…
typeofis an operator, not a function, so you don’t need the parentheses around it.