0

Suppose an object is declared as follows

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

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

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
Sahasrangshu Guha
  • 672
  • 2
  • 11
  • 29
  • 6
    Let me just ask - **why** do you need the name of the variable? *Usually*, if you *need* the name, you're probably doing something "wrong" – Ian Jul 29 '14 at 14:24
  • 1
    You could always add a variable to the object `name: 'object1',`, but yeah, Ian asks the right question. – Andy Jul 29 '14 at 14:26
  • 4
    What should it return if `obj1 = obj2 = obj3 = { ... }`. I'd say you are approaching the problem (whatever that is) incorrectly. – techfoobar Jul 29 '14 at 14:29

1 Answers1

2

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"
dfsq
  • 191,768
  • 25
  • 236
  • 258
  • 3
    I was heading in this direction, but this only returns the constructor name and not the name of the instance which I think is what the OP is after. – Andy Jul 29 '14 at 14:33
  • @Andy I think you are right. Will delete it, once OP make it clear what he wants. – dfsq Jul 29 '14 at 14:34
  • I'd guess that the OP is attempting to mimic Java's `getName()` function (which returns the name of a class via reflection), but is confused about how "classes" are implemented in JS. I think you've given the best answer that could be given to such a question. – JDB Jul 29 '14 at 14:37