Sahasrangshu Guha
Sahasrangshu Guha

Reputation: 683

Getting the name of variable which holds an object, from the function resides in the object

Suppose an object is declared as follows

var object1 = {
    getName: function() {
        alert(name)
    }
};

Is there a way to alert "object1" from getName?

Upvotes: 0

Views: 53

Answers (1)

dfsq
dfsq

Reputation: 193261

If you declare an object like object literal then the answer is no, you can't get variable name. You can however declare it using constuctor:

function Obj() {
    this.getName = function() {
        console.log(this.constructor.name);
    }
}
new Obj().getName(); // "Obj"

Upvotes: 2

Related Questions