javascriptmetaprogrammingmetasyntactic-variable

Javascript getVariableName


This is my first post.

I'm trying to do some basic meta-programming with javascript, and I was wondering if there is a way of get the id of a particular object and with that id, access to the variable name, or get simply the variable name of a particular object. I wanna recreate a situation in which you first create every single html in a web page, and append to some of the html tags events associated to a particular class -example class Person-. for example: Supposed the next code:

var someFunction = function(someText){alert(someText);}
function SomeClassFunction(){
     this.aClassFunction = someFunction;
}

var aVariableName = new SomeClassFunction();

and in the HTML code suppose I have the next piece of code.

<html>
  <head>
    <title></title>
  </head>
  <body>
    <div onclick="aVariableName.aClassFunction('Some text to show in alert');">
    </div>
  </body>
</html>

Then, as you may notice the onclick event uses the aVariableName I created before, but because I first create the name of the variable and then append the name in the code cause I knew aVariableName was the name of that object. What I wanna do or implement is to create the text above in html without know the variable name of an specific object. I have surfed on the net but, unfortunately I haven't found anything about it.


Solution

  • i dont know how to get the name of a variable from the code its self without doing a whole load of work parsing stuff, which will get messy, and i'd shoot someone for this.

    var someValue;
    var foo = function() { someValue; }
    alert((foo + '')); // this is now a string, use substr to extract variable name
    

    You know you can set events like this in javascript someElement.onclick = someFunction so you dont really need to know the name of the variable if all you're doing is setting an event handler.