如何在 JavaScript 中获取实例名称?

Gus*_*avo 3 javascript class instance

如果我创建一个这样的类:

function MyClass(input){
  // construct something;
  var myInstanceName = ???
}
Run Code Online (Sandbox Code Playgroud)

创建实例时我需要实例的名称......

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();
}
Run Code Online (Sandbox Code Playgroud)

只需将其放在带有 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();
}
Run Code Online (Sandbox Code Playgroud)

shm*_*uli 5

简单代码示例:

 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"
Run Code Online (Sandbox Code Playgroud)