Nodejs Object Type Check type()

Here you can find the source of type()

Method Source Code

Object.defineProperty(Object.prototype, 'type', {
    get() {/* ww  w. j  a  va 2 s. c  o  m*/
        // <this> is set to the constructor function of the instance that called this method
        // also check the constructor
        let value
        if(this.val) {
           value = this.val
        }
        else {
           value = this.valueOf()
        }
        let is_arr  = value instanceof Array || Array.isArray(value)
        let is_num  = value instanceof Number || !isNaN(value) 
        let is_bool = value instanceof Boolean || typeof value == 'boolean'
        let is_str  = value instanceof String || typeof value == 'string'
        let is_fn   = value instanceof Function || typeof value == 'function'
        let is_rx   = value instanceof RegExp
        let is_obj  = typeof value == 'object'
        // define undefined, null, symbol, and the custom data types
         
        if(is_str) {
           return 'string'
        }
        if(is_bool) {
           return 'boolean'
        }
        if(is_num) {
           return 'number'
        }
        if(is_rx) {
           return 'regex'
        }
        if(is_arr) {
            return 'array'
        }
        if(is_fn) {
          return 'function'
        }
        if(is_obj) {
          return 'object'
        }
      // implementare anche per le istanze di costruttori personalizzati
    }
})

Related

  1. isBoolean()
    Object.prototype.isBoolean = function () {
        return (typeof (this.valueOf()) === 'boolean')
    };
    
  2. isInteger()
    Object.prototype.isInteger = function () {
        var number = parseFloat(this.valueOf());
        return number.isNumber() && /^-?\d+$/.test(String(number));
    };
    
  3. isJSON()
    Object.prototype.isJSON = function () {
        try {
            JSON.parse(this);
            return true;
        } catch (e) {
            return false;
    
  4. isTypeOf(type)
    Object.prototype.isTypeOf = function(type) {
      var that = this;
      return Object.prototype.toString.call(that) === '[object ' + type + ']';