Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
199
rated 0 times [  200] [ 1]  / answers: 1 / hits: 16990  / 7 Years ago, sat, march 18, 2017, 12:00:00

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.


More From » javascript

 Answers
34

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'




[#58494] Thursday, March 16, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
taliac

Total Points: 84
Total Questions: 114
Total Answers: 114

Location: Morocco
Member since Fri, May 22, 2020
4 Years ago
;