The built-in typeof operator has some major screwups:
> typeof null
>> "object"
> typeof []
>> "object"
> typeof /blah/
>> "function"
I think it would be nice to have two wrapper functions around typeof
that fix its inconsistencies:
- basetype() - that would return one of the 6 basic types as defined
in ECMAScript specification ('number', 'string', 'boolean', 'null',
'undefined', 'object')
- type() - that besides 6 basic data types would additionally return
'array', 'function', 'regExp' or 'element'
After having investigated several implementations (most notably the
one from Crockford's "Remedial":
http://javascript.crockford.com/remedial.html) I have put together
this code:
/**
* Base type check (returns either 'number', 'string', 'boolean',
'null', 'undefined' or 'object')
*/
window.basetype = function(variable) {
var type = typeof variable;
if (variable === null) {
return 'null';
}
else if (type === 'function') {
return 'object';
}
else {
return type;
}
}
/**
* Type check (returns either 'number', 'string', 'boolean', 'null',
'undefined',
* 'object', 'array', 'function', 'regExp' or 'element'
*/
window.type = function(variable) {
var type = typeof variable;
if (type === 'object') {
if (variable === null) {
return 'null';
}
else if (toString.call(variable) === '[object Array]') {
return 'array';
}
else if ( !!(variable && variable.nodeType === 1) ) {
return 'element';
}
}
if (type === 'function') {
if ( variable instanceof RegExp ) {
return 'regExp';
}
}
return type;
}
My questions:
- Why so many frameworks are deciding to provide a set of checkers
such as isArray(), isNull(), isFunction() instead of single type()
function? Is performance gain really noticeable when using simple type
checkers?
- Are there any major mistakes that would hinder performance or
reliability of the functions above? Could they be improved any
further?
--
To view archived discussions from the original JSMentors Mailman list:
http://www.mail-archive.com/[email protected]/
To search via a non-Google archive, visit here:
http://www.mail-archive.com/[email protected]/
To unsubscribe from this group, send email to
[email protected]