0

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?

0

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.