Getting the object variable name in JavaScript

前端 未结 3 710
野性不改
野性不改 2020-12-02 00:51

I am creating a JavaScript code and I had a situation where I want to read the object name (string) in the object method. The sample code of what I am trying to achieve is s

3条回答
  •  佛祖请我去吃肉
    2020-12-02 01:10

    This is not possible in JavaScript. A variable is just a reference to an object, and the same object can be referenced by multiple variables. There is no way to tell which variable was used to gain access to your object. However, if you pass a name to your constructor function you could return that instead:

    // Define my object
    function TestObject (name) {
        return {
            getObjectName: function() {
                return name
            }
        };
    }
    
    // create instance
    var a1 = TestObject('a1')
    var a2 = TestObject('a2')
    
    console.log(a1.getObjectName()) //=> 'a1'
    
    console.log(a2.getObjectName()) //=> 'a2'

提交回复
热议问题