我无法找到实现此目的的动态/通用方法。 我想要的是从对象函数中获取保存启动对象的变量的名称。
没有例子很难解释这一点。 我不知道这样的过程是否有一个“技术/程序”名称。
举个例子
我启动一个对象作为..
var jTest = new boom('hi');
我有对象构造函数作为..
function boom(message){
console.log(message+' - '+objname);
// what I want in the value of 'objname' is 'jTest'
// I want to know dynamically what is the name of the variable that is going to hold this object instance (in this case 'jTest').
// so that when I create html elements from this object
// and they later have events I get a way to access the object instance
// from inside the event functions.
// for eg
this.ref = document.createElement('div');
this.ref.setAttribute('style','display:block;width:100px;height:100px;background:#f00');
this.ref.setAttribute('data-obj',objname); // <- this obj name contains jTest or whatever name this object instance is stored as
// then if i saved a name 'jTest' inside the element attr as a ref for later
this.body.appendChild(this.ref);
this.ref.addEventListener('click',(function(event){
// this - over here it refers to the element not the object instance jTest or any other forsaken name
jTest.dance(); // now i want to run an object property called dance()
// how to do this dynamically...?
// you need to know the name of the variable that holds this object instance
// so that you can call its property
// this is where the attr "data-obj" value 'jTest' will help !
}),true);
}
我想知道变量的字面名称(在本例中为“jTest”),它包含从对象内部对新创建的对象实例的引用。
这样我就可以为我从对象内部创建的 html 元素设置标识符、类 (.jTest)。
所以当我在那些 html 元素上发生事件时 我将知道是哪个实例创建了它们,并且我可以访问相应的对象函数。
希望这是可以理解的。当我有新的想法来解释自己时,我会尝试更新描述。 还建议我解决此问题的其他方法“一种了解和调用从元素事件(悬停/单击)函数内部创建元素的对象实例的方法”。
最佳答案
我想你应该看看这个问题:Determine name of a JavaScript object instance's class
但是,对象 jTest 不是“名称”,而是指向该对象的指针。这里的大问题应该是:为什么您想知道指向您正在使用的实例的指针的名称?您始终可以使用 this
将您正在使用的实例传递给另一个对象。 (参见:http://www.quirksmode.org/js/this.html)
关于javascript - 如何从对象 : Javascript 中获取保存对象实例的变量名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26880616/