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 methodsmyClass.prototype.global = this// create a global variable referring to an objectvar myVar = new myClass()myVar.myName() // returns "myVar"请注意,这是一个丑陋的技巧,不应在生产代码中使用。如果引用一个对象的变量多于一个,则无法确定将得到哪个变量。它只会搜索全局变量,因此如果变量在函数本地是无效的。通常,如果需要命名,则应在创建名称时将其传递给构造函数。
编辑
:为了响应您的澄清,如果您需要能够引用事件处理程序中的某些内容,则不应按名称引用它,而应添加直接引用该对象的函数。这是我快速举过的一个简单示例,它显示出与您尝试执行的操作类似的操作:
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()}


