栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Javascript中以字符串形式获取类对象的名称?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Javascript中以字符串形式获取类对象的名称?

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/407999.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号