448,548 Members | 1,183 Online
Need help? Post your question and get tips & solutions from a community of 448,548 IT Pros & Developers. It's quick & easy.

# Is It Possible to Retrieve A Variable Name of a Parameter Passed to a Function?

 P: 9 Hi My question is NOT the topic covered in this thread: https://bytes.com/topic/javascript/answers/809155-howto-get-variables-name-not-value-introspection Here's my scenario: Expand|Select|Wrap|Line Numbers function Billiard(){      // position      this.position;        // strike another billiard      this.strike = function(targetBilliard, strength){           targetBilliard.position += strength;           alert(targetBilliard.number + ' position: ' + targetBilliard.position);         }     }   // make 2 billiards var b1 = new Billiard; b1.position = 8;   var b2 = new Billiard; b2.position = 5;   // b1 strikes b2 b1.strike(b2, 5);   What i'd like to happen is, in the Strike function, when b1 strikes b2, display the variable-name of the targetBilliard in the alert, "b2". Something like: NameOf(targetBilliard) i realize this may not be possible, but i'm guessing would require some sort of memory access? thx! Jan 14 '16 #1

you can retrieve that by implementing a function like the following (getVarName):

Expand|Select|Wrap|Line Numbers
1. function getVarName(val, scope) {
2.     var ret = null;
3.
4.     for (var i in scope) {
5.         var r = scope[i];
6.
7.         if (r === val) {
8.             ret = i;
9.             break;
10.         }
11.     }
12.
13.     return ret;
14. };
15.
16. function Billiard() {
17.     // position
18.     this.position;
19.
20.     // strike another billiard
21.     this.strike = function(targetBilliard, strength) {
22.         var tgt = getVarName(targetBilliard, window);
23.
24.         targetBilliard.position += strength;
25.
26.         console.log(
27.            tgt + ' position: ' + targetBilliard.position
28.         );
29.     };
30. };
31.
32. // make 2 billiards
33. var b1 = new Billiard;
34. b1.position = 8;
35.
36. var b2 = new Billiard;
37. b2.position = 5;
38.
39. // b1 strikes b2
40. b1.strike(b2, 5);
what do we use here? you register the variables b1, b2 globally in the window scope. the function getVarName makes use of that now and retrieves the property names of the scope and if it finds an identical object in that scope it returns the property's name.

cheers :)

PS: its working here because objects are assigned to the variables in question - if it would be primitive values then this wouldn't work correctly because such values are not passed by reference in JavaScript. Basically i would give the objects a name when constructing them so it would be much easier to identify them for example:

Expand|Select|Wrap|Line Numbers
1. function Billiard(name) {
2.     this.name = name;
3.
4.     // ...
5. }
and then you could simply ask for:

Expand|Select|Wrap|Line Numbers
1. targetBilliard.name