3

If I create a class like this:

function MyClass(input){
  // construct something;
  var myInstanceName = ???
}

I'll need the name of the instance when creating an instance...

var MyInstance = new MyClass("Make Something");

Need to know myInstanceName (="MyInstance" in this case) because there is a method that creates buttons and the "onclick" must call a method of this instance.

I tried "this.name" but it returns undefined... How do I get this value?

EDIT: Here is a tested working example:

function MyClass(WhereGoesTheButton){
    this.myName = "Test"; // <-- here is the issue
    this.idButton = WhereGoesTheButton;
    //
}
MyClass.prototype.createButton = function(){
    document.getElementById(this.idButton).innerHTML = '<button id="myId" onclick="'+this.myName+'.callBack(this);">Press Here</button>';
}
MyClass.prototype.callBack = function(who){
    alert("Button "+who.id+" has been pressed!");
}
var Test = new MyClass("testArea");
//
function ini(){
    Test.createButton();
}

Just put it in a page with body onload ini() and some div to create the button.

It works, but alternatives with better practices are welcome!

EDIT 2: this will do the job, although we still got no name of the instance:

var MyClassId = 0;
function MyClass(WhereGoesTheButton){
    this.myButtonId = "MyClass"+String(MyClassId);
    MyClassId++;
    this.idButton = WhereGoesTheButton;
    //
}
MyClass.prototype.createButton = function(){
    var me = this;
    document.getElementById(this.idButton).innerHTML = '<button id="'+this.myButtonId+'" >Press Here</button>';
    document.getElementById(this.myButtonId).addEventListener("click", function(e){ me.callBack(this); }, false);
}
MyClass.prototype.callBack = function(who){
    alert("Button "+who.id+" has been pressed!");
}
var Test = new MyClass("testArea");
//
function ini(){
    Test.createButton();
}
3
  • 2
    If you need to know the name of the variable, you are 99.99% of the time doing something you shouldn't. Commented Sep 30, 2013 at 21:02
  • What if I'm 0.01% ??? Ok, an alternative way of doing the same thing is welcome. In AS3 I get the variable by "target" property of the event, but it seams there isn't such thing in JS... Commented Sep 30, 2013 at 22:50
  • Check out my answer to this duplicate question at: stackoverflow.com/questions/12972262/… Commented Apr 25, 2014 at 13:39

4 Answers 4

5

Simple code example:

 function Parent(){
        // custom properties
    }

    Parent.prototype.getInstanceName = function(){
        for (var instance in window){
            if (window[instance] === this){
                return instance;
            }
        }
    };

    var child = new Parent();

    console.log(child.getInstanceName()); // outputs: "child"
Sign up to request clarification or add additional context in comments.

2 Comments

It seams will work only if the instance were created in the root. Also, might slow down if got to look at all window objects. But it's interesting, I will keep this code near...
Thank you. This was exactly what i have been searching for! =)
1

Need to know myInstanceName (="MyInstance" in this case) because there is a method that creates buttons and the "onclick" must call a method of this instance.

Why do you need the variable name for that? Your method can reference the current instance with this.

However, inside a click handler this will be the clicked element. Assuming you're bind the event somewhat like this:

someElement.addEventListener('click', this.someMethod, false);

... you can change it to:

var that = this;
someElement.addEventListener('click', function(e) {
    that.someMethod()
}, false);

There are other possible solutions too, like bind and the EventListener interface.

5 Comments

As described, the class create some buttons in the page, when clicked, it must call a method of the instance of the class that created those buttons. Is there another way of doing this?
@GustavoPinent Yes, there is another way. Please check my updated answer.
I think this way is better, however, unfortunately, it doesn't work because I got to identify the button with a unique ID so I can use addEventListener on it. Maybe a trick is numbering as instances are been created, but with the name of the instance will be easier, I think.
@GustavoPinent how are you binding the click event?
I'm not using bind, not sure if will work and may not be accepted by older browsers. But your suggestion is almost right! I did a numbering (will be above) and now it works. In the future, "this.name" will do the job, but right now we got only the hack.
0

this refers to the instance when inside the constructor. However, note well that in Javascript, this is determined dynamically when a function is called. So if you are eg. setting up handlers using this in a constructor without judicious use of bind, you will likely run into errors.

See here for more info on this

Comments

0

My best suggestion if you really need the name, just pass it as an optional argument in the constructor. Then if provided can set a member property this.instanceName = passedNameArgument then access it later for error handling or whatever your needs are.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.