Skip to content Skip to sidebar Skip to footer

Why Javascript Typeof Returns Always "object"

Where am I doing wrong? I would wait 'Class' as a result of this code but it doesn't: This is from object function:

Solution 1:

Tyepof doesnt work like that, it only returns built in types. You could try:

this.constructor.name==="Class";

It will check all the way up the prototype chain to see if this or any prototype of this is Class. So if OtherType.prototype=Object.create(Class); then it'll be true for any OtherType instances. Does NOT work in < IE9

or

thisinstanceof Class

But that will not check the entire prototype chain.

Here is a list of return values typeof can return

Here is an answer about getting the type of a variable that has much more detail and shows many ways it can break.

Solution 2:

Because JavaScript knows only the following types :

Undefined - "undefined"

Null - "object"

Boolean - "boolean"

Number - "number"

String - "string"

Host object (provided by the JS environment) - Implementation-dependent

Function object (implements [[Call]] in ECMA-262 terms) - "function"

E4X XML object - "xml"

E4X XMLList object - "xml"

Any other object - "object"

You can find more here

Read this thread to find how you can get the object name

Solution 3:

object.constructor.name will return constructor's name. Here is an example:

function SomeClass() {
    /* code */
}
var obj = new SomeClass();
// obj.constructor.name == "SomeClass"

Be aware that you need to use named functions, if you assign anonymous functions to variables, it will be an empty string...

varSomeClass = function () {
    /* code */
};
var obj = newSomeClass();
// obj.constructor.name == ""

But you can use both, then the named function's name will be returned

var SomeClassCtor = function SomeClass() {
    /* code */
};
var obj = new SomeClassCtor();
// obj.constructor.name == "SomeClass"

Solution 4:

You may try this as well

functiongetType(obj){
    if (obj === undefined) { return'undefined'; }
    if (obj === null) { return'null'; }
    return obj.constructor.name || Object.prototype.toString.call(obj).split(' ').pop().split(']').shift().toLowerCase();
}

An Example Here.

functionMyClass(){}
console.log(getType(newMyClass)); // MyClassconsole.log(getType([])); // Arrayconsole.log(getType({})); // Objectconsole.log(getType(newArray)); // Arrayconsole.log(getType(newObject)); // Objectconsole.log(getType(newDate)); // Dateconsole.log(getType(newError));  // Error

Post a Comment for "Why Javascript Typeof Returns Always "object""