如何在 JavaScript 中获取实例名称
How to get the instance name in JavaScript?
如果我创建一个这样的类:
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);
还有其他可能的解决方案,例如bind
和EventListener
接口。
this
在构造函数中引用实例。但是,请注意,在Javascript中,this
是在调用函数时动态确定的。所以如果你是例如。在构造函数中使用this
设置处理程序而不明智地使用 bind
,您可能会遇到错误。
有关this
的更多信息,请参阅此处
如果您真的需要名称,我的最佳建议是将其作为构造函数中的可选参数传递即可。然后,如果提供,可以设置成员属性this.instanceName = passedNameArgument
然后稍后访问它以进行错误处理或任何您的需求。
- 使用jQuery获取Dropzone实例/对象
- 如何在速度模板中获取LiferayPortlet实例id
- 如何获取单选按钮的多个实例的选定单选按钮值
- 无法在XUL Firefox扩展中获取TinyMCE的实例
- 如何在另一个组件中获取指令/组件实例
- 如何从一个友好的iframe中获取iframe实例
- 更新Redux状态&然后在同一实例中获取更新状态
- 从对象实例中获取变量名称
- 可以获取模板实例值,但不能将其用于其他函数
- 突出显示所选文本并同时获取实例
- 如何获取先前创建的Google图表的实例
- 获取JSON标记(JAVASCRIPT)中的所有JSON实例
- jquery获取类的下一个实例的值
- 获取 CodeMirror 实例
- 如何通过元素选择器获取tinyMCE编辑器实例
- 剑道网格:在Angular指令中获取一个实例
- 如何获取谷歌图表的实例
- 使用ID获取AmChart的实例
- 从实例获取主干视图的父类
- 使用实例获取所选标记的id