Find out instance variable name out of itself - javascript

I've created a JavaScript Class just as following:
function MyClass() {
this.myProp = '';
}
MyClass.prototype.myTestFunction = function() {
alert('test');
}
Now, I instantiate this class.
var myTestInstance = new MyClass();
myTestInstance.myTestFunction();
This outputs an alert with 'test'.
Now I want to have the variable name 'myTestInstance' into the function 'myTestFunction()' without having to pass it as a parameter.
Is it somehow possible to find out the variable name of the instance from inside the called function?
Thank you for your help!
EDIT: Just to add information why I would need this: Every instance I create in my real project is a special HTML table. In the header fields are sort-buttons for every column. Therefore I added dynamically a link-element with href='javascript:myTableInstance.sort()'. To print this dynamically IN the instance, I needed the variable name.
Would there be another, better solution?

No, it does not make sense in any way. First of all, instance is not tied to a single variable (it might be referenced by many variables, it could be referenced by none - perhaps as a member of some array) - so the question "what is the name of the variable that stores the instance" is unanswerable. Secondly, the scope of myTestFunction and myTestInstance could be very different. In a usual case myTestFunction would not "see" the scope that has myTestInstance defined - so knowing the name of the variable would not help.
You should just use "this" inside myTestFunction.

Related

Unityscript class extend variable scope

I'm not all that well versed in JavaScript and I've got a scope problem that I can't find a reference on:
class a
{
var CommonNameVar;
}
class b extends a
{
var CommonNameVar;
function Something(){
CommonNameVar = "somevalue";
}
}
How do I specifically reference CommonNameVar in b and not a (i.e. reference a specific scope of variables)?
It turns out that I'm also not familiar with unityscript and I've made a rather cardinal mistake of assuming that just because this has a .js on the file, that this is javascript (sound like an old sketch from Bob Newhart).
I'll post a new question formatted correctly for the context and declare this one dead.
You can't hide CommonNameVar from the scope it is declared in. But, to make it available to b, you need to create it as this.CommonNameVar so it becomes an instance property and will inherit, otherwise, it's just a local variable and won't inherit.
The this keyword ensures that you'll always get the value of the property that is associated with the instance.
And, your syntax needs a bit of work as classes declare properties within them, not just "loose" elements.
So, with the code below, when an instance of a is made, this will reference one instance and CommonNameVar will be something and when an instance of b is made, b.CommonNameVar will also be something (because of inheritance), until/unless b.Something() is executed, in which case b.CommonNameVar will then be somevalue, while a.CommonNameVar will remain something.
class a {
this.CommonNameVar = "something";
}
class b extends a {
this.Something = function() {
this.CommonNameVar = "somevalue";
}
}
this can get considerably more tricky depending on your code structure and you can read about that here.

Can data added in javascript arrays be accessed later?

I am new to Javascript, is there a way to store data in an array and be able to access it later. Example :
I have created an array
If I click on my HTML file button (add a question), a function generates a random Id for a question block (like id="13819").
It is then added to an array of question Id's
Once the function is done running, does the Id stay in the array once added? Or does the array reset when the function called again?
If it does reset, how do you make it to not reset?
It depends on where your variable is created. If it is a top level variable(global) you will be able to add new data during the whole users session. On the other side if that variable is created inside a function it will be erased every time you call that function.
Short answer: Yes
Long answer: It depends
It depends on where you created the array. This is known as the scope of the array.
If it is inside the function, the scope of the array is inside the function, so only things inside the function can access the array. Once the function is finished, the array no longer exists.
You can create it in the global scope, i.e. as an attribute of the global window object, but you should try as much as possible to limit the scope of your variables, so that you don't pollute the global namespace

Get variable name from within object instance [duplicate]

This question already has an answer here:
Find out instance variable name out of itself
(1 answer)
Closed 19 days ago.
I want to be able to access the var name of this class instance from inside a method.. Can I set the actual variable name as a string on the constructor or something?
var myClass = function(filePath){
this.run = function(){
// I want to access the string "x"
console.log( this.variableName ); // ????
};
};
var x = new myClass("./sayHi.js");
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.

Get name of instance of a class within the class

Here is what I want:
var Validator = function () {
this.do = function () {
alert(INTANCENAME); /// SHOULD BE 'FOO'
}
}
var FOO = new Validator().do();
Is it possibe to implement in Javascript?
The truth is there is no point of doing that, the only way I can hardly think is to loop all window or scope objects and check some kind of equality with the current object, something like
this.do = function () {
for(var key in window) {
if(this === window[key]) {
alert(key);
}
}
};
In order to work call it after you assign it.
var FOO = new Validator();
FOO.do();
Another issue that can come up is that an instance (a reference) can be stored in various variables so maybe will not get what you expect.
The literal answer to your question would be:
Use (new Error()).stack to get information on the line and the function where the do() method was called.
Use JS parser (e.g. Esprima) to find out what variable it was called on (if any, the method itself might be assigned to a variable).
I do not recommend doing this though.
There's no way to directly do what you're asking for here. Objects themselves are not in any defined by their matching variable name - in fact it's possible to have objects that exist that are not directly assigned to a variable, and multiple variables assigned to the same object.
The javascript interpreter uses our variable names as identifiers to help with the code execution, but once it's running the variable name makes no difference to the running javascript program, as it's probably been reduced to a memory reference by the time it's executing, completely separated from the original code that you wrote.
Edit: Answer by yannis does kind of simulate this, but it relies on working with variables available in a specific scope - what I ment was that there's no direct way to do this from within the object itself as per your example in the question.

What is the different between a parameter and a local variable?

Apologies for what must seem like a very stupid question.
I'm currently working through codecadamy, and this is throwing me off:
var greeting = function(name) {
name = "sausage";
console.log(name);
};
greeting(name);
I understand that I will get sausage
Why don't I just write var name = "sausage";? What is the difference?
The name in function(name) is a parameter. That is, it is used to pass data into the function. But, parameters are local variables. Assigning a value to name inside the function is a little strange though. I would assume you want to do something like this:
var greeting = function(name) {
console.log(name);
};
greeting("sausage");
In this version of the code you are passing the value "sausage" into the function via the parameter name. This is useful because you can call the function many times and each time the function may print a different value depending on what you pass.
In your function definition:
function(name) {
name is already being declared. It is a parameter for the function. If you want to change name, you can, but you don't need to use var to declare it as a new variable.
On the other hand, if you wanted to add, say, flavor, you should use var then since it is not already defined.
var flavor = 'savory';
In this case, flavor is a local variable and name is a parameter. A parameter is a type of local variable that is declared with the function declaration, but a local variable isn't necessarily a parameter because it may be declared elsewhere in the function.
Parameters are a general programming construct and are necessary to do anything sane in the world programming (dealing with masses of global variables is not sane.
var name would declare a new variable in the function scope that would override the value of the parameter name, so you would not be able to use the parameter anymore.
The CodeAcadamy example is a bit strange because it's rare that you want to override a parameter's value -- especially before you have used it.
Technically, there is no real difference.
Without giving you the huge background here, you have to understand that in the underlaying implementation, a special object (not a javascript object, on C/C++ level) is formed which is called Activation Object (ES3) or Lexical Environment Record (ES5).
However, this hash / object structure is used to store
variables declared by var
formal parameters
function declarations
As you can see, both var variables and parameters are stored in this structure.
This construct is most likely used to have somewhat default values for not passed in arguments. In a real world example, this would probably look more like
var greeting = function( name ) {
name = name || 'default';
console.log( name );
};
greeting('john'); // 'john'
greeting(); // 'default'

Categories