Getting the object variable name in JavaScript

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'

Tags:

Javascript