【发布时间】:2015-01-08 22:19:09
【问题描述】:
我无法找到实现此目的的动态/通用方法。 我想要的是从对象函数中获取保存启动对象的变量的名称。
如果没有例子,这有点难以解释。 我不知道这样的程序是否有“技术/程序”名称。
举个例子
我启动一个对象为..
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 元素上有事件时 我会知道是哪个实例创建了它们,并且我可以访问相应的对象函数。
希望这是可以理解的。当我有新的想法来解释自己时,我会尝试更新描述。 还建议我解决此问题的其他方法'一种了解和调用从元素事件(悬停/单击)函数内部创建元素的对象实例的方法'。
【问题讨论】:
-
jTest 不包含任何名称,但它包含指向新创建对象的地址
-
正如我所说的......它很难解释和理解......我想知道保存的变量名称'jTest',它包含从对象内部对新创建的对象实例的引用实例。这样我就可以为我从对象内部创建的 html 元素设置一个标识符(.jTest)。所以当我在这些 html 元素上有事件时,我知道是哪个实例创建了它们,我可以访问对象函数。
标签: javascript oop object instance instance-variables