Design & Download
Your JS Library
in Seconds!!!

Snippet: addTypeOf() - Augmenting the Type Checker

Written by Christopher West (cwest) on January 01, 2016.
Add custom types to the typeOf() function.
var addTypeOf;
(function(baseTypeOf, EXTRA_TYPES, l) {
  addTypeOf = function(constructor, name) {
    for (var i = 0; i < l && EXTRA_TYPES[i][1] != name; i++);
    EXTRA_TYPES[i] = [constructor, name];
    l = EXTRA_TYPES.length;
    if (l == 2) {
      YourJS.typeOf = typeOf = function(value) {
        var test, i = 0, typeName = baseTypeOf(value), argv = arguments, argc = argv.length;
        if (typeName == 'Object') {
          for (; i < l; i++) {
            if (EXTRA_TYPES[i][0] == value.constructor) {
              typeName = EXTRA_TYPES[i][1];
              break;
            }
          }
        }
        for (i = argc; --i && ((typeof(test = argv[i]) == 'string' || typeOf(test) != 'RegExp') ? typeName != test : !test.test(typeName)); );
        return argc > 1 ? !!i : typeName;
      };
    }
  };
})(typeOf, [[Object, 'Object']], 1);

addTypeOf(...) API Documentation

Add custom types to the typeOf() function.

Parameters

  1. constructor {Function}:
    The constructor of the class to be recognized by typeOf().
  2. name {string}:
    The name of the class as it should be returned by typeOf().

Examples

If you wanted to add jQuery as a recognized type you could do the following:
addTypeOf(jQuery, 'jQuery');
Now if you wanted to test if something was a jQuery object you could simply do the following:
var jDivs = $('div.name');
var isJQuery = typeOf(jDivs, 'jQuery');
Of course you can also simply return the type name as follows:
var jDivs = $('div.name');
var typeName = typeOf(jDivs);
console.log(typeName); // "jQuery"