venerdì, ottobre 06, 2006

typeof and Typeof

Dean Edwards point me out that typeof doesn’t always work so I come to a solution to this issue.

function isFunction(x){
typeof(x)==="function" &&
(typeof(x.toSource)==="undefined" || x.toSource().charAt(0)!="/")


basically it control if is a function (typeof(x)==="function")
and if is a gecko browser (typeof(x.toSource)==="undefined")
it control if is a RegExp(x.toSource().charAt(0)!="/").

So I wrote my simple Typeof function

function Typeof(what){
case Object:return "Object";
case Function:return "Function";
case Array:return "Array";
case String:return "String";
case Boolean:return "Boolean";
case Number:return "Number";
case RegExp:return "RegExp";
case Date:return "Date";
case Error:return "Error";
case Math:return "object";
case null:return "null";
if(typeof(what)==="function" && (typeof(what.toSource)!=="undefined" && what.toSource().charAt(0)=="/"))return "object"; //regex for moz
return typeof(what);

Enjoy ;)

2 commenti:

Andrea Giammarchi ha detto...

function is(obj, type){return obj.constructor == type};

is({}, Object), // true
is("Hello", String), // true
is(new String, String), // true
is(function(){return false}, Function), // true
is(new Function(), Function), // true
is(/test/, Function), // false
is(/test/, RegExp), // true
is(new RegExp, Function), // false
is(new RegExp, RegExp), // true
is(RegExp, RegExp), // false
is(RegExp, Function) // true

Andrea Giammarchi ha detto...

for undefined or null vars too ...

function is(obj, type){
return typeof(obj) === "undefined" || obj === null ?
obj === type :
obj.constructor === type