Get the name of an object's type

前端 未结 20 2256
忘掉有多难
忘掉有多难 2020-11-21 22:37

Is there a JavaScript equivalent of Java\'s class.getName()?

20条回答
  •  死守一世寂寞
    2020-11-21 22:39

    Lodash has many isMethods so if you're using Lodash maybe a mixin like this can be useful:

      // Mixin for identifying a Javascript Object
    
      _.mixin({
          'identify' : function(object) {
            var output;
              var isMethods = ['isArguments', 'isArray', 'isArguments', 'isBoolean', 'isDate', 'isArguments', 
                  'isElement', 'isError', 'isFunction', 'isNaN', 'isNull', 'isNumber', 
                  'isPlainObject', 'isRegExp', 'isString', 'isTypedArray', 'isUndefined', 'isEmpty', 'isObject']
    
              this.each(isMethods, function (method) {
                  if (this[method](object)) {
                    output = method;
                    return false;
                  }
              }.bind(this));
          return output;
          }
      });
    

    It adds a method to lodash called "identify" which works as follow:

    console.log(_.identify('hello friend'));       // isString
    

    Plunker: http://plnkr.co/edit/Zdr0KDtQt76Ul3KTEDSN

提交回复
热议问题