Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
633 views
in Technique[技术] by (71.8m points)

Getting the object variable name in JavaScript

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 shown below:

// Define my object
var TestObject = function() {
    return {
        getObjectName: function() {
            console.log( /* Get the Object instance name */ );
        }
    };
}

// create instance
var a1 = TestObject();
var a2 = TestObject();

a1.getObjectName(); // Here I want to get the string name "a1";

a2.getObjectName(); // Here I want to get the string name "a2";

I am not sure if this is possible in JavaScript. But in case it is, I would love to hear from you guys how to achieve this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...