Javascript Object Prototype Check Object type

Description

Javascript Object Prototype Check Object type


// Adding an improved typeof feature to our Object class
Object.prototype.getType = function() {
    if (typeof(this) == "object") {
        if (this.constructor == Array) return "array";
        if (this.constructor == Date) return "date";
        if (this.constructor == RegExp) return "regex";
        return "object";
    }//from  w  w  w.jav a  2s.c  o  m
    return typeof(this);  
}
// Testing our new getType() function
let myArray = new Array();
let myObj = new Object();
let myRegex = new RegExp();
let myDate = new Date();

console.log(myArray.getType());    // "array"
console.log(myObj.getType());    // "object"
console.log(myRegex.getType());    // "regex"
console.log(myDate.getType());    // "date"



PreviousNext

Related