Julian Avar
Julian Avar

Reputation: 476

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?

Upvotes: 1

Views: 65

Answers (2)

Akxe
Akxe

Reputation: 11495

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!

Upvotes: 2

gurvinder372
gurvinder372

Reputation: 68393

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.

Upvotes: 6

Related Questions