Shog9 是对的,这并没有多大意义,因为一个对象可以被多个变量引用。如果您并不真正关心这一点,而您只想找到引用该对象的全局变量之一的名称,则可以执行以下操作:
function myClass() {
this.myName = function () {
// search through the global object for a name that resolves to this object
for (var name in this.global)
if (this.global[name] == this)
return name
}
}
// store the global object, which can be referred to as this at the top level, in a
// property on our prototype, so we can refer to it in our object's methods
myClass.prototype.global = this
// create a global variable referring to an object
var myVar = new myClass()
myVar.myName() // returns "myVar"
请注意,这是一个丑陋的 hack,不应在生产代码中使用。如果引用一个对象的变量不止一个,你就分不清会得到哪一个。它只会搜索全局变量,因此如果变量是函数的局部变量,它将不起作用。一般来说,如果你需要命名一些东西,你应该在创建它时将名称传递给构造函数。
编辑:为了回应您的澄清,如果您需要能够从事件处理程序中引用某些内容,则不应按名称引用它,而是添加一个直接引用该对象的函数。这是我提出的一个快速示例,我认为它显示了与您正在尝试做的事情类似的事情:
function myConstructor () {
this.count = 0
this.clickme = function () {
this.count += 1
alert(this.count)
}
var newDiv = document.createElement("div")
var contents = document.createTextNode("Click me!")
// This is the crucial part. We don't construct an onclick handler by creating a
// string, but instead we pass in a function that does what we want. In order to
// refer to the object, we can't use this directly (since that will refer to the
// div when running event handler), but we create an anonymous function with an
// argument and pass this in as that argument.
newDiv.onclick = (function (obj) {
return function () {
obj.clickme()
}
})(this)
newDiv.appendChild(contents)
document.getElementById("frobnozzle").appendChild(newDiv)
}
window.onload = function () {
var myVar = new myConstructor()
}