如何在 JavaScript 中获取实例名称

How to get the instance name in JavaScript?

本文关键字:实例 获取 JavaScript      更新时间:2023-09-26

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

function MyClass(input){
  // construct something;
  var myInstanceName = ???
}

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

var MyInstance = new MyClass("Make Something");

需要知道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();
}

简单的代码示例:

 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"

需要知道myInstanceName(在本例中为="MyInstance"),因为有一个创建按钮的方法,并且"onclick"必须调用此实例的方法。

为什么需要变量名称?您的方法可以使用 this 引用当前实例。

但是,在单击处理程序中,this将是单击的元素。假设您绑定的事件有点像这样:

someElement.addEventListener('click', this.someMethod, false);

。您可以将其更改为:

var that = this;
someElement.addEventListener('click', function(e) {
    that.someMethod()
}, false);

还有其他可能的解决方案,例如bindEventListener接口。

this在构造函数中引用实例。但是,请注意,在Javascript中,this是在调用函数时动态确定的。所以如果你是例如。在构造函数中使用this设置处理程序而不明智地使用 bind ,您可能会遇到错误。

有关this的更多信息,请参阅此处

如果您真的需要名称,我的最佳建议是将其作为构造函数中的可选参数传递即可。然后,如果提供,可以设置成员属性this.instanceName = passedNameArgument然后稍后访问它以进行错误处理或任何您的需求。