gpt4 book ai didi

javascript - 如何在 Javascript 中将类对象的名称作为字符串获取?

转载 作者:IT王子 更新时间:2023-10-29 03:09:13 26 4
gpt4 key购买 nike

假设我像这样在 Javascript 中实例化一个对象:

var myObj = new someObject();

现在,是否可以从其中一个类方法中获取 var 对象的名称作为字符串 'myObj'


其他详细信息(已编辑):

我想要获取持有对象引用的变量名称的原因是我的新 myObj 会在页面上创建一个新的可点击的 DIV需要调用函数 myObj.someFunction()。当我插入新的 DIV 时,我需要知道保存对象引用的变量的名称。是否有更好的方法?


您是对的,很抱歉混淆了术语。

我想要获取持有对象引用的变量名称的原因是我的新 myObj 会在需要调用函数 myObj.someFunction() 的页面上创建一个新的可点击 DIV。当我插入新的 DIV 时,我需要知道持有对象引用的变量的名称。是否有更好的方法?

最佳答案

Shog9 是对的,这个问题没有多大意义,因为一个对象可以被多个变量引用。如果您真的不关心这一点,而只想找到引用该对象的全局变量之一的名称,则可以执行以下 hack:

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()
}

关于javascript - 如何在 Javascript 中将类对象的名称作为字符串获取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/789675/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com