Skip to content

Instantly share code, notes, and snippets.

@co3moz
Last active March 24, 2016 14:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save co3moz/2fee40916efc8ba461ac to your computer and use it in GitHub Desktop.
Save co3moz/2fee40916efc8ba461ac to your computer and use it in GitHub Desktop.
Small size object type checker for js
var check = function(o) {
return (o == null) ? null : o.constructor == Function ? o.name == "" ? "Callback" : "Class_" + o.name : o.constructor.name;
};
// how can be different check and typeof
// checkfor check result typeof result
check(null); //null "object"
check(undefined); //null "undefined"
check(1); //"Number" "number"
check([]); //"Array" "object"
check({}); //"Object" "object"
check(true); //"Boolean" "boolean"
check("yello"); //"String" "string"
check(function(){}); //"Callback" "function"
function Test() {}
check(Test); //"Class_Test" "function"
check(new Test); //"Test" "object"
@co3moz
Copy link
Author

co3moz commented Mar 24, 2016

example

function myClass (value) { // var myClass = function() { # is invalid!
  this.value = value;
}

var myValue = 5;

function doSomethingWithMyValue(thing) {
  var value = check(thing);
  if(value == 'myClass')  value = thing.value;
  else if(value == 'Number') value = thing;
  return value * 2;
}

doSomethingWithMyValue(new myClass(5)); // 10
doSomethingWithMyValue(myValue); // 10

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment