How to get a JavaScript object's class?

前端 未结 18 2328
一生所求
一生所求 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条回答
  •  遥遥无期
    2020-11-22 16:09

    Question seems already answered but the OP wants to access the class of and object, just like we do in Java and the selected answer is not enough (imho).

    With the following explanation, we can get a class of an object(it's actually called prototype in javascript).

    var arr = new Array('red', 'green', 'blue');
    var arr2 = new Array('white', 'black', 'orange');
    

    You can add a property like this:

    Object.defineProperty(arr,'last', {
      get: function(){
        return this[this.length -1];
      }
    });
    console.log(arr.last) // blue
    

    But .last property will only be available to 'arr' object which is instantiated from Array prototype. So, in order to have the .last property to be available for all objects instantiated from Array prototype, we have to define the .last property for Array prototype:

    Object.defineProperty(Array.prototype,'last', {
      get: function(){
        return this[this.length -1];
      }
    });
    console.log(arr.last) // blue
    console.log(arr2.last) // orange
    

    The problem here is, you have to know which object type (prototype) the 'arr' and 'arr2' variables belongs to! In other words, if you don't know class type (prototype) of the 'arr' object, then you won't be able to define a property for them. In the above example, we know arr is instance of the Array object, that's why we used Array.prototype to define a property for Array. But what if we didn't know the class(prototype) of the 'arr'?

    Object.defineProperty(arr.__proto__,'last2', {
      get: function(){
        return this[this.length -1];
      }
    });
    console.log(arr.last) // blue
    console.log(arr2.last) // orange
    

    As you can see, without knowing that 'arr' is an Array, we can add a new property just bu referring the class of the 'arr' by using 'arr.__proto__'.

    We accessed the prototype of the 'arr' without knowing that it's an instance of Array and I think that's what OP asked.

提交回复
热议问题