Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to get the instance name in JavaScript?
    text
    copied!<p>If I create a class like this:</p> <pre><code>function MyClass(input){ // construct something; var myInstanceName = ??? } </code></pre> <p>I'll need the name of the instance when creating an instance...</p> <p>var MyInstance = new MyClass("Make Something");</p> <p>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.</p> <p>I tried "this.name" but it returns undefined... How do I get this value?</p> <p>EDIT: Here is a tested working example:</p> <pre><code>function MyClass(WhereGoesTheButton){ this.myName = "Test"; // &lt;-- here is the issue this.idButton = WhereGoesTheButton; // } MyClass.prototype.createButton = function(){ document.getElementById(this.idButton).innerHTML = '&lt;button id="myId" onclick="'+this.myName+'.callBack(this);"&gt;Press Here&lt;/button&gt;'; } MyClass.prototype.callBack = function(who){ alert("Button "+who.id+" has been pressed!"); } var Test = new MyClass("testArea"); // function ini(){ Test.createButton(); } </code></pre> <p>Just put it in a page with body onload ini() and some div to create the button.</p> <p>It works, but alternatives with better practices are welcome!</p> <p>EDIT 2: this will do the job, although we still got no name of the instance:</p> <pre><code>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 = '&lt;button id="'+this.myButtonId+'" &gt;Press Here&lt;/button&gt;'; 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(); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload