HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Extension of JavaScript "typeof"

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
javascripttypeofextension

Problem

I've written this "little" typeof extension for my JS. What do you think about it?

Its aim is to provide a single reliable typeof in JavaScript, consistent between native vars and objects. I've tested it both in FF 4+, IE 7+, Chrome 12, Safari 5. Also, if you have a different browser (also the version), can you test it?

typeOf = function(e) {
  if (typeof e === "undefined") {
    return "undefined";
  } else if (typeof e === "object") {
    if (e === null) {
      // null è un oggetto
      return "null";
    } else if (e instanceof String) {
      return "string";
    } else if (e instanceof Number) {
      return "number";
    } else if (e instanceof Boolean) {
      return "boolean";
    } else if (e instanceof Date) {
      return "date";
    } else if (e instanceof RegExp) {
      return "regexp";
    } else if (e instanceof Error) {
      return "error";
    } else if (e.isArray
                || e instanceof Array) {
      return "array";
    } else if (e instanceof Window) {
      return "window";
    } else if (e.nodeType) {
      switch (e.nodeType) {
        case 1:
          return "element";
        case 2:
          return "attribute";
        case 3:
          return "text";
        case 9:
          return "document";
      }
    } else if (e.call) {
      return "function";
    }
  } else if (typeof e === "function") {
    if (e.call) {
      return "function";
    } else if (e instanceof RegExp) {
      // V8
      return "regexp";
    }
  }

  return typeof e;
};

Solution

I don't think much of it, to be honest. It's not as reliable as you might think, because once you start passing objects between contexts (e.g. different windows) it will fail miserably. Add to that the fact that

Object.prototype.toString.call();


could do most of your work for you and your extension starts to look a little redundant and unnecessary.

Here's a detailed article on this problem: Cross-context isArray and Internet Explorer

Code Snippets

Object.prototype.toString.call(<any value>);

Context

StackExchange Code Review Q#9184, answer score: 7

Revisions (0)

No revisions yet.