Get the name of an object's type

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

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

相关标签:
20条回答
  • 2020-11-21 23:05

    Ok, folks I've been slowly building a catch all method for this over some years lol! The trick is to:

    1. Have a mechanism for creating classes.
    2. Have a mechanism for checking all user created classes, primitives and values created/generated by native constructors.
    3. Have a mechanism for extending user created classes into new ones so that the above functionality permeates through your code/application/library/etc..

    For an example (or to see how I dealt with the problem) look at the following code on github: https://github.com/elycruz/sjljs/blob/master/src/sjl/sjl.js and search for:

    classOf =, classOfIs =, and or defineSubClass = (without the backticks (`)).

    As you can see I have some mechanisms in place to force classOf to always give me the classes/constructors type name regardless of whether it is a primitive, a user defined class, a value created using a native constructor, Null, NaN, etc.. For every single javascript value I will get it's unique type name from the classOf function. In addition I can pass in actual constructors into sjl.classOfIs to check a value's type in addition to being able to pass in it's type name as well! So for example:

    ``` // Please forgive long namespaces! I had no idea on the impact until after using them for a while (they suck haha)

    var SomeCustomClass = sjl.package.stdlib.Extendable.extend({
        constructor: function SomeCustomClass () {},
        // ...
    }),
    
    HelloIterator = sjl.ns.stdlib.Iterator.extend( 
        function HelloIterator () {}, 
        { /* ... methods here ... */ },
        { /* ... static props/methods here ... */ }
    ),
    
    helloIt = new HelloIterator();
    
    sjl.classOfIs(new SomeCustomClass(), SomeCustomClass) === true; // `true`
    sjl.classOfIs(helloIt, HelloIterator) === true; // `true`
    
    var someString = 'helloworld';
    
    sjl.classOfIs(someString, String) === true; // `true`
    
    sjl.classOfIs(99, Number) === true; // true
    
    sjl.classOf(NaN) === 'NaN'; // true
    
    sjl.classOf(new Map()) === 'Map';
    sjl.classOf(new Set()) === 'Set';
    sjl.classOfIs([1, 2, 4], Array) === true; // `true`
    
    // etc..
    
    // Also optionally the type you want to check against could be the type's name
    sjl.classOfIs(['a', 'b', 'c'], 'Array') === true; // `true`!
    sjl.classOfIs(helloIt, 'HelloIterator') === true; // `true`!
    

    ```

    If you are interested in reading more on how I use the setup mentioned above take a look at the repo: https://github.com/elycruz/sjljs

    Also books with content on the subject: - "JavaScript Patterns" by Stoyan Stefanov. - "Javascript - The Definitive Guide." by David Flanagan. - and many others.. (search le` web).

    Also you can quickly test the features I'm talking about here: - http://sjljs.elycruz.com/0.5.18/tests/for-browser/ (also the 0.5.18 path in the url has the sources from github on there minus the node_modules and such).

    Happy Coding!

    0 讨论(0)
  • 2020-11-21 23:06

    If anyone was looking for a solution which is working with jQuery, here is the adjusted wiki code (the original breaks jQuery).

    Object.defineProperty(Object.prototype, "getClassName", {
        value: function() {
            var funcNameRegex = /function (.{1,})\(/;
            var results = (funcNameRegex).exec((this).constructor.toString());
            return (results && results.length > 1) ? results[1] : "";
        }
    });
    
    0 讨论(0)
提交回复
热议问题