如果我创建一个像这样的类:
function MyClass(input){
// construct something;
var myInstanceName = ???
}
在创建实例时,我需要知道实例的名称...
var MyInstance = new MyClass("制造一些东西");
需要知道myInstanceName(在这种情况下为“MyInstance”),因为有一个方法会创建按钮,“onclick”必须调用此实例的方法。
我尝试过“this.name”,但它返回未定义...如何获得此值?
编辑:这是一个经过测试的工作示例:
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();
}
只需将其放入一个带有body onload ini()和一些div的页面中即可创建按钮。
它可以工作,但欢迎使用更好的实践替代!
编辑2:这将完成任务,尽管我们仍然没有实例的名称:
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();
}