简体   繁体   中英

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:

在此输入图像描述

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

this instanceof 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.

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

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...

var SomeClass = function () {
    /* code */
};
var obj = new SomeClass();
// 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"

You may try this as well

function getType(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.

function MyClass(){}
console.log(getType(new MyClass)); // MyClass
console.log(getType([])); // Array
console.log(getType({})); // Object
console.log(getType(new Array)); // Array
console.log(getType(new Object)); // Object
console.log(getType(new Date)); // Date
console.log(getType(new Error));  // Error

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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