【问题标题】:Can i use constructor.name to detect types in JavaScript我可以使用 constructor.name 来检测 JavaScript 中的类型吗
【发布时间】:2011-08-12 11:11:25
【问题描述】:

我可以使用“构造函数”属性来检测 JavaScript 中的类型吗? 或者有什么我应该知道的。

例如:var a = {}; a.constructor.name; // outputs "Object"

var b = 1; b.constructor.name; // outputs "Number"

var d = new Date(); d.constructor.name; // outputs "Date" not Object

var f = new Function(); f.constructor.name; // outputs "Function" not Object

只有在参数arguments.constructor.name; //outputs Object like first example上使用它

我经常看到开发人员使用:Object.prototype.toString.call([])

Object.prototype.toString.call({})

【问题讨论】:

    标签: javascript types detection typeof


    【解决方案1】:

    您可以使用typeof,但有时它会返回misleading results。而是使用Object.prototype.toString.call(obj),它使用对象的内部[[Class]] 属性。你甚至可以为它做一个简单的包装器,所以它的作用类似于typeof

    function TypeOf(obj) {
      return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
    }
    
    TypeOf("String") === "string"
    TypeOf(new String("String")) === "string"
    TypeOf(true) === "boolean"
    TypeOf(new Boolean(true)) === "boolean"
    TypeOf({}) === "object"
    TypeOf(function(){}) === "function"
    

    不要使用obj.constructor,因为它会被更改,尽管您可能可以使用instanceof 来查看它是否正确:

    function CustomObject() {
    }
    var custom = new CustomObject();
    //Check the constructor
    custom.constructor === CustomObject
    //Now, change the constructor property of the object
    custom.constructor = RegExp
    //The constructor property of the object is now incorrect
    custom.constructor !== CustomObject
    //Although instanceof still returns true
    custom instanceof CustomObject === true
    

    【讨论】:

    • @gruentee [需要引用] 在 IE11 中对我来说效果很好
    【解决方案2】:

    您可以使用typeof 例如:typeof("Hello")

    【讨论】:

    • typeof 实际上不会那么精确,因为alert ( typeof new Number() ) // Object
    • 同意,因为 JavaScript 不是一种类型语言,你不能指望它的 typeof 是精确的 :)
    • 不,JavaScript 是一种松散类型的语言。
    • 你确定吗??? typeof opertaor 是最好的选择,以确定变量是否已被实例化(或者它是否存在,也存在一些问题)但如果我有类似的东西:var a = function() {}; var b = new a(); typeof a; //outputs objecttypeof new Array(); //outputs object。那我怎么用它来精确呢?
    猜你喜欢
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-08
    • 2023-03-13
    • 2010-10-01
    • 1970-01-01
    相关资源
    最近更新 更多