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

时间:2013-09-30 20:59:57

标签: javascript class instance

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

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

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

var MyInstance = new MyClass(“Make Something”);

需要知道myInstanceName(在这种情况下为“MyInstance”),因为有一个方法可以创建按钮,而“onclick”必须调用此实例的方法。

我尝试了“this.name”,但它返回undefined ......如何获得此值?

编辑:这是一个经过测试的工作示例:

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

4 个答案:

答案 0 :(得分:3)

简单的代码示例:

 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"

答案 1 :(得分:1)

  

需要知道myInstanceName(在这种情况下为“MyInstance”),因为有一个方法可以创建按钮,而“onclick”必须调用此实例的方法。

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

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

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

...您可以将其更改为:

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

还有其他可能的解决方案,例如bindEventListener interface

答案 2 :(得分:0)

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

See here了解有关this

的更多信息

答案 3 :(得分:0)

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