9
9

More than 5 years have passed since last update.

typeof/instanceofをより使いやすく

Posted at

色んな所罵倒されてるjavascript/coffeescriptの型判定関数ですが。
パパッと使い勝手のいい関数で補完しましょう。

方法一、JavaScript Garden参照

typeOf = (obj) ->
  Object.prototype.toString.call(obj)[8...-1]

方法二、CoffeeScript Cookbook参照

要注意!
ここでのエラーはオブジェクトと判定されます(ある意味正しい)

typeOf(new Error()) === 'object'

typeOf = (obj) ->
  if obj == undefined or obj == null
    return String obj
  classToType = new Object
  for name in "Boolean Number String Function Array Date RegExp".split(" ")
    classToType["[object " + name + "]"] = name.toLowerCase()
  myClass = Object.prototype.toString.call obj
  if myClass of classToType
    return classToType[myClass]
  return "object"
9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9