Get the name of an object's type

前端 未结 20 2303
忘掉有多难
忘掉有多难 2020-11-21 22:37

Is there a JavaScript equivalent of Java\'s class.getName()?

20条回答
  •  猫巷女王i
    2020-11-21 22:47

    The kind() function from Agave.JS will return:

    • the closest prototype in the inheritance tree
    • for always-primitive types like 'null' and 'undefined', the primitive name.

    It works on all JS objects and primitives, regardless of how they were created, and doesn't have any surprises. Examples:

    Numbers

    kind(37) === 'Number'
    kind(3.14) === 'Number'
    kind(Math.LN2) === 'Number'
    kind(Infinity) === 'Number'
    kind(Number(1)) === 'Number'
    kind(new Number(1)) === 'Number'
    

    NaN

    kind(NaN) === 'NaN'
    

    Strings

    kind('') === 'String'
    kind('bla') === 'String'
    kind(String("abc")) === 'String'
    kind(new String("abc")) === 'String'
    

    Booleans

    kind(true) === 'Boolean'
    kind(false) === 'Boolean'
    kind(new Boolean(true)) === 'Boolean'
    

    Arrays

    kind([1, 2, 4]) === 'Array'
    kind(new Array(1, 2, 3)) === 'Array'
    

    Objects

    kind({a:1}) === 'Object'
    kind(new Object()) === 'Object'
    

    Dates

    kind(new Date()) === 'Date'
    

    Functions

    kind(function(){}) === 'Function'
    kind(new Function("console.log(arguments)")) === 'Function'
    kind(Math.sin) === 'Function'
    

    undefined

    kind(undefined) === 'undefined'
    

    null

    kind(null) === 'null'
    

提交回复
热议问题