• Fixing the JavaScript typeof operator


    https://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/
    javascript 类型判断函数
    var toType = function(obj) { return ({}).toString.call(obj).match(/s([a-zA-Z]+)/)[1].toLowerCase() }


    A Better Way?

    [[Class]]

    Every JavaScript object has an internal property known as [[Class]] (The ES5 spec uses the double square bracket notation to represent internal properties, i.e. abstract properties used to specify the behavior of JavaScript engines). According to ES5, [[Class]] is “a String value indicating a specification defined classification of objects”. To you and me, that means each built-in object type has a unique non-editable, standards-enforced value for its [[Class]] property. This could be really useful if only we could get at the [[Class]] property…

    Object.prototype.toString

    …and it turns out we can. Take a look at the ES 5 specification for Object.prototype.toString…

    1. Let O be the result of calling ToObject passing the this value as the argument.
    2. Let class be the value of the [[Class]] internal property of O.
    3. Return the String value that is the result of concatenating the three Strings "[object "class, and "]".

    In short, the default toString function of Object returns a string with the following format…

    [object [[Class]]]

    …where [[Class]] is the class property of the object.

    Unfortunately, the specialized built-in objects mostly overwrite Object.prototype.toStringwith toString methods of their own…

    [1,2,3].toString(); //"1, 2, 3"
    
    (new Date).toString(); //"Sat Aug 06 2011 16:29:13 GMT-0700 (PDT)"
    
    /a-z/.toString(); //"/a-z/"
    

     
    …fortunately we can use the call function to force the generic toString function upon them…

    Object.prototype.toString.call([1,2,3]); //"[object Array]"
    
    Object.prototype.toString.call(new Date); //"[object Date]"
    
    Object.prototype.toString.call(/a-z/); //"[object RegExp]"
    

     
    Introducing the toType function

    We can take this technique, add a drop of regEx, and create a tiny function – a new and improved version of the typeOf operator…

  • 相关阅读:
    两数之和
    IDEA类的旁边有个对勾
    Markdown 常用语法
    GitLab 使用指南(IntelliJ IDEA)
    Python yield 用法
    Mac for MySQL 5.7 安装教程
    Mac Hadoop2.6(CDH5.9.2)伪分布式集群安装
    Hive 建外链表到 Hbase(分内部表、外部表两种方式)
    hive grouping sets 等聚合函数
    hive row_number等窗口分析函数
  • 原文地址:https://www.cnblogs.com/oxspirt/p/10197077.html
Copyright © 2020-2023  润新知