简体   繁体   中英

is there such thing as function.name for objects

So I was wondering if there is a way to use function.name but for objects. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name

What I mean by this is to have something like this:

function myFunction() {}

console.log(myFunction.name); // logs "myFunction"

// but like

var myObj = {};

console.log(myObj.name); // logs "myObj"

and if it is possible, how would it handle something like this?

var myObj = {};
var myObj2 = {};

console.log(myObj2.name); // logs "myObj" or "myObj2" or both?

Two things

  1. Object don't have name property by default, unless you specify the same while defining the object,

for example

var myObj = {
  name : "myObj"
};
  1. In myObj2.name , myObj2 is not the name of the object, it is the name of reference (variable) to object.

Short answer? No.

On the other hand, as you may know, global variables are part of window variable. Therefore, you could do something like:

function findName(obj, scope){
    if(scope === void 0){
        scope = window
    }
    for (prop in scope) {
        if(scope.hasOwnProperty(prop) && scope[prop] == obj){
            return prop
        }
    }
}

NOTE: This is extremly inefficent way to get variable name!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM