Can I set the type of a Javascript object?

后端 未结 5 1580
忘了有多久
忘了有多久 2021-02-02 00:15

I\'m trying to use some of the more advanced OO features of Javascript, following Doug Crawford\'s \"super constructor\" pattern. However, I don\'t know how to set and get types

5条回答
  •  感动是毒
    2021-02-02 00:36

    if you're using a constructor, a better solution than instanceOf, would be this :

    Object.toType = function(obj) {
      return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
    }
    
    
    toType({a: 4}); //"object"
    toType([1, 2, 3]); //"array"
    (function() {console.log(toType(arguments))})(); //arguments
    toType(new ReferenceError); //"error"
    toType(new Date); //"date"
    toType(/a-z/); //"regexp"
    toType(Math); //"math"
    toType(JSON); //"json"
    toType(new Number(4)); //"number"
    toType(new String("abc")); //"string"
    toType(new Boolean(true)); //"boolean"
    toType(new CreateBicycle(2)); //"createbicycle"
    

    The explanation of WHY it's the best way to do it relies in This post.

提交回复
热议问题