How to get the object name of an object in JavaScript

问题: This is NOT about how to get keys or values In the example below: var exampleObject = {startIndex: 1, stopIndex: 2}; How can I get the exact name "exampleObject" of th...

问题:

This is NOT about how to get keys or values

In the example below:

var exampleObject = {startIndex: 1, stopIndex: 2};

How can I get the exact name "exampleObject" of this object? I have tried exampleObject.constructor.name but all I got was "Object" as the result.


回答1:

You cannot.*

First of all, more than one variables can point to the same object. Variables are only references, not containers. There is no one true name for an object. Here's an example:

function makeExample() () {
  var x = {startIndex: 1, stopIndex: 2};
  var y = x;
  return y;
}

var z = makeExample();

In the above code, what should the name of the object be? x, y, z? All of these variables don't contain a copy of the object, they point to the same object. exampleObject is the name of the variable, not the name of the object.

A variable name is just a label to be used by the programmer, not by code. That is not the same thing as a property, which is data stored inside an object and identified by a key which is either a string or a symbol. If the object needs to have a name, then it should be part of its own properties:

var exampleObject = { name: "exampleObject" };

*Technically, any variable created with var in the global scope of a script that is not executed as a module will be added to the window object. That is a relic of the past and you should not rely on this - in fact, modern JS code should use let to create variables which do not have this behavior.


回答2:

The only way I know of doing this is with this custom function:

var returnObjectName = function (object) {
  var objectName;
  for(var i in window){
    if(window[i] === object) {
      objectName = i;
    }
  }
return objectName;
}
(Note this function might mess up if there is an object with the same value as the object name you are trying to find!)

If I did something wrong do not just downvote my answer but also tell me what I did wrong.

  • 发表于 2019-02-17 20:10
  • 阅读 ( 157 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除