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();
}
Gustavo
  • 1,673
  • 4
  • 24
  • 39
  • 2
    If you need to know the name of the variable, you are 99.99% of the time doing something you shouldn't. – adeneo Sep 30 '13 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... – Gustavo Sep 30 '13 at 22:50
  • Check out my answer to this duplicate question at: http://stackoverflow.com/questions/12972262/javascript-get-name-of-instance-of-class/23294728#23294728 – Kmeixner Apr 25 '14 at 13:39

4 Answers4

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"
shmuli
  • 5,086
  • 4
  • 32
  • 64
  • 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... – Gustavo Apr 15 '15 at 22:34
  • Thank you. This was exactly what i have been searching for! =) – Really Nice Code Jul 17 '17 at 22:12
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.

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
  • 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? – Gustavo Sep 30 '13 at 22:51
  • @GustavoPinent Yes, there is another way. Please check my updated answer. – bfavaretto Oct 01 '13 at 00:16
  • 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. – Gustavo Oct 01 '13 at 01:18
  • @GustavoPinent how are you binding the click event? – bfavaretto Oct 01 '13 at 01:20
  • 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. – Gustavo Oct 01 '13 at 01:49
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

Community
  • 1
  • 1
Wyatt
  • 2,491
  • 15
  • 12
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.