How to get a JavaScript object's class?

前端 未结 18 2334
一生所求
一生所求 2020-11-22 15:44

I created a JavaScript object, but how I can determine the class of that object?

I want something similar to Java\'s .getClass() method.

18条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 16:22

    In keeping with its unbroken record of backwards-compatibility, ECMAScript 6, JavaScript still doesn't have a class type (though not everyone understands this). It does have a class keyword as part of its class syntax for creating prototypes—but still no thing called class. JavaScript is not now and has never been a classical OOP language. Speaking of JS in terms of class is only either misleading or a sign of not yet grokking prototypical inheritance (just keeping it real).

    That means this.constructor is still a great way to get a reference to the constructor function. And this.constructor.prototype is the way to access the prototype itself. Since this isn't Java, it's not a class. It's the prototype object your instance was instantiated from. Here is an example using the ES6 syntactic sugar for creating a prototype chain:

    class Foo {
      get foo () {
        console.info(this.constructor, this.constructor.name)
        return 'foo'
      }
    }
    
    class Bar extends Foo {
      get foo () {
        console.info('[THIS]', this.constructor, this.constructor.name, Object.getOwnPropertyNames(this.constructor.prototype))
        console.info('[SUPER]', super.constructor, super.constructor.name, Object.getOwnPropertyNames(super.constructor.prototype))
    
        return `${super.foo} + bar`
      }
    }
    
    const bar = new Bar()
    console.dir(bar.foo)
    

    This is what that outputs using babel-node:

    > $ babel-node ./foo.js                                                                                                                   ⬡ 6.2.0 [±master ●]
    [THIS] [Function: Bar] 'Bar' [ 'constructor', 'foo' ]
    [SUPER] [Function: Foo] 'Foo' [ 'constructor', 'foo' ]
    [Function: Bar] 'Bar'
    'foo + bar'
    

    There you have it! In 2016, there's a class keyword in JavaScript, but still no class type. this.constructor is the best way to get the constructor function, this.constructor.prototype the best way to get access to the prototype itself.

提交回复
热议问题