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();
}