1

I have a class and I want from inside the class to save as a class variable the name of the object using the class:

var xxx = new MyClass(); // on the constructor this.name should be init to "xxx"

Ive already tried this approach:

How to get class object's name as a string in Javascript?

But I can't get it work from the class constructor itself.

Community
  • 1
  • 1
JuanCB
  • 305
  • 1
  • 3
  • 11

1 Answers1

2

xxx is just a variable holding a reference to the Object in memory. If you want to give that object a property of name, you should pass it as an argument.

var xxx = new MyClass( 'xxx' );

var MyClass = function( name ) {
    this.name = name || undefined;
};

You could keep a hash of your objects to avoid creating different variables each time:

var myHash = {};

var MyClass = function( name ) {
    if( !name ) throw 'name is required';
    this.name = name;
    myHash[ name ] = this;
    return this;
};
//add static helper
MyClass.create = function( name ) {
    new MyClass( name );
};    

//create a new MyClass
MyClass.create( 'xxx' );

//access it
console.log( myHash.xxx )​;

Here is a fiddle: http://jsfiddle.net/x9uCe/

Paul
  • 12,392
  • 4
  • 48
  • 58
  • Im bck on the start since accessing the variable name for the object was to evade passing it as an argument, guess no other way! Thanks anyway! – JuanCB Aug 21 '12 at 23:49
  • @JuanCB: What if you'd have multiple variables referring to the same object? Or the object is an element in an array only? It just does not work that way. – Felix Kling Aug 22 '12 at 01:37