dltypeof - Custom JS typeof operator - DHTML Lab
JavaScript Programming: dltypeof() v1.0,
An Introduction
Produced by Peter BelesisPrerequisite
To fully appreciate the functionality of dltypeof(), you should be familiar with the JS operator it attempts to replace: typeof().
The typeof() operator is defined in:
The JS typeof() problem
Anyone who has written a JS application of any complexity will have come across the frustrations associated with the limitations of the typeof() operator.
The typeof() operator performs as defined, but we are left wishing that it could provide us with more meaningful information, or that a similar, more powerful, operator existed to help identify object types to our applications.
For example, if we have a function that expects either a string, an array or null as its single argument, how do we identify the argument's type in our function? Our function could look like this:
function myFunction( vArgument ) { var sTypeOf = typeof( vArgument ); switch ( sTypeOf ) { case "string": var sArgumentType = sTypeOf; break; case "object": if( vArgument == null ) { var sArgumentType = "null"; } else { if( vArgument.constructor == Array ) { var sArgumentType = "array"; } } } ...my statements... }
The typeof() operator will return only these values:
"number" "string" "boolean" "function" "undefined" "object"
Even though JS includes the following native object types:
Object, Function, Array, String, Boolean, Number, Math, Date, RegExp, Error, null
we cannot identify all of them with typeof(), nor any other JS operator.
Array, Date, Math, RegExp, Error and null objects are all identified as "object"
The situation gets even worse when we attempt to identify our own custom objects, or DOM elements, DOM collections and DOM text nodes, which are also identified as "object".
Enter dltypeof()
The dltypeof() works just like typeof(), only it returns more meaningful identifiers for objects. Use dltypeof() in your applications, either through an external file, dltypeof.js, or copy and paste the function into your own scripts.
Code Discussion
We will discuss dltypeof(), statement-by-statement in a future article, after we have used it for awhile and added any object types missed on this first go-through.
Script Download
dltypeof() can be downloaded in a zip file, or simply copied from the final page of this article.
Download: dltypeof.zip
Now let's look at the values dltypeof() returns.
Send a comment or suggestion to Peter Belesis
Created: August 23, 2004Revised: August 23, 2004
URL: https://webreference.com/dhtml/column68/