在JavaScript中获取对象变量名称 [英] Getting the object variable name in JavaScript

查看:49
本文介绍了在JavaScript中获取对象变量名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个JavaScript代码,遇到一种情况,我想在object方法中读取对象名称(字符串).我试图实现的示例代码如下所示:

I am creating a JavaScript code and I had a situation where I want to read the object name (string) in the object method. The sample code of what I am trying to achieve is shown below:

// Define my object
var TestObject = function() {
    return {
        getObjectName: function() {
            console.log( /* Get the Object instance name */ );
        }
    };
}

// create instance
var a1 = TestObject();
var a2 = TestObject();

a1.getObjectName(); // Here I want to get the string name "a1";

a2.getObjectName(); // Here I want to get the string name "a2";

我不确定在JavaScript中是否可行.但万一是这样,我很想听听你们如何实现这一目标.

I am not sure if this is possible in JavaScript. But in case it is, I would love to hear from you guys how to achieve this.

推荐答案

在JavaScript中这是不可能的.变量只是对对象的引用,同一对象可以由多个变量引用.无法确定使用哪个变量来访问您的对象.但是,如果将name传递给构造函数,则可以返回该值:

This is not possible in JavaScript. A variable is just a reference to an object, and the same object can be referenced by multiple variables. There is no way to tell which variable was used to gain access to your object. However, if you pass a name to your constructor function you could return that instead:

// Define my object
function TestObject (name) {
    return {
        getObjectName: function() {
            return name
        }
    };
}

// create instance
var a1 = TestObject('a1')
var a2 = TestObject('a2')

console.log(a1.getObjectName()) //=> 'a1'

console.log(a2.getObjectName()) //=> 'a2'

这篇关于在JavaScript中获取对象变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆