假设我在Javascript中实例化一个对象,如下所示:
var myObj = new someObject();
Run Code Online (Sandbox Code Playgroud)
现在,是否可以'myObj'从其中一个类方法中获取var对象的名称作为字符串?
我想得到保持对象引用的变量名称的原因是我的new myObj会DIV在页面上创建一个需要调用函数的新的clickable myObj.someFunction().当我插入新的时,DIV我需要知道保持对象引用的变量的名称.有没有更好的方法呢?
你是对的,对不起术语的混淆.
我想得到保持对象引用的变量名称的原因是我的新myObj将在页面上创建一个需要调用函数myObj.someFunction()的新的可点击DIV.当我插入新的DIV时,我需要知道保持对象引用的变量的名称.有没有更好的方法呢?
Bri*_*ell 43
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"
Run Code Online (Sandbox Code Playgroud)
请注意,这是一个丑陋的黑客,不应该在生产代码中使用.如果有一个以上的变量引用一个对象,你就无法分辨出你会得到哪一个.它只会搜索全局变量,因此如果变量是函数的局部变量,它将不起作用.通常,如果需要命名,则应在创建时将名称传递给构造函数.
编辑:为了回应您的澄清,如果您需要能够从事件处理程序引用某些内容,则不应该通过名称引用它,而是添加直接引用该对象的函数.这是一个快速的例子,我掀起了一些类似的东西,我认为,你正在尝试做的事情:
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()
}
Run Code Online (Sandbox Code Playgroud)
Sho*_*og9 20
简短的回答:不,myObj不是对象的名称,它是包含对象引用的变量的名称 - 您可以拥有任意数量的其他变量来保存对同一对象的引用.
现在,如果它是你的程序,那么你制定规则:如果你想说任何给定的对象只会被一个变量引用,并且在代码中努力强制执行,那么只需在对象上设置一个属性即可.变量的名称.
那就是说,我怀疑你所要求的实际上是你真正想要的.也许更详细地描述你的问题......?
Pedantry: JavaScript没有类.someObject是一个构造函数.给定对象的引用,您可以使用构造函数属性获取对创建它的函数的引用.
您正在寻找的答案可以在这里找到:JavaScript回调范围(以及对SO上的许多其他问题的回应 - 这对JS新手来说是一个常见的混淆点).您只需要在闭包中包含对对象成员的调用,该闭包保留对上下文对象的访问.
xag*_*ars 11
您可以使用.toString()将构造函数转换为字符串:
function getObjectClass(obj){
if (typeof obj != "object" || obj === null) return false;
else return /(\w+)\(/.exec(obj.constructor.toString())[1];}
Run Code Online (Sandbox Code Playgroud)