Pass the variable name as a parameter when you construct it
var myClass = function(assigned_name,filePath){
this.variableName = assigned_name
this.run = function(){
console.log( this.variableName );
}
}
var x = new myClass('x','./sayHi.js');
x.run()
Output:
'x'
Useful for:
While many people say this is pointless, I have run into a situation where I need it. And a side-note, many jQuery operations rely on the principle of knowing what its own variable name is. It is always '$'. And people refer to '$' from inside a jQuery method when assigning anonymous functions to onclick events without realizing that it is exactly what your question is asking for.
You will need this if your myClass() object dynamically assigns event handlers that call-back to your specific class instance, as these calls are often reliant on information saved in your specific class variable. Since your myClass() function isn't as wide-spread as jQuery, you can't count on it always being assigned to the same variable, like '$'.
Passing its own assigned variable name to itself when it is constructed is the best way I've found to let my class instance know what its global reference is.
thiskeyword. And you should define your methods on the prototype of the constructor not inside it.