nagoon97’s Weblog

you can actually do alot with javascript!

Improved typeof for the exact object type March 10, 2008

Filed under: ajax,javascript — nagoon97 @ 3:06 pm
Tags: , ,

When I first started writing scripts in Javascript, the typeof() operator did not capture much of my attention.

Because of my experience in other programming languages, I naturally believed that the operator would give me the exact name and this firm belief cost me many hours of debugging.

And when I realized that the operator won’t even tell me whether a given object is an instance of Array or Date, it was very frustrating because I’ve designed the entire script based on the assumption that the operator would provide me the exact object type.

So, I wrote the following short function, which privodes the constructor’s function name when it was given an object.

/**
 * You can find more about this function at
 * http://nagoon97.com/gettype/
 *
 * Copyright (c) 2008 Andy G.P. Na <nagoon97@gmail.com>
 * The source code is freely distributable under the terms of an MIT-style license.
 */
function getType(v){
 var result = typeof(v);
 if (result == "object"){
  result = "@unknown";
  if(v.constructor){
   var sConstructor = v.constructor.toString();
   var iStartIdx = sConstructor.indexOf(' ' ) + 1;
   var iLength = sConstructor.indexOf('(' ) - iStartIdx;
 
   var sFuncName = sConstructor.substr(iStartIdx, iLength);
   if (iStartIdx && sFuncName) result = sFuncName;
  }
 }
 return result.toLowerCase();
}

“@” was added infront of the word “unknown” because the function name can actually be “unknown” and this confusion can be avoided by adding “@”, which cannot be used for function names.

 

About these ads
 

3 Responses to “Improved typeof for the exact object type”

  1. [...] note that you need to include getType() function that I have posted earlier HERE. getType() is used to give methodOverloading() function the ability to overload method with user [...]

  2. Karol Says:

    It would be nice to wrap the result in toLowerCase to have a value more similar to what native typeof would return.

    getType({})
    => ‘object’ //not ‘Object’

  3. nagoon97 Says:

    Good point, Karol.
    I edited the function according to your suggestion.
    Thank you :-)


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

Join 33 other followers