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.

1
  • 2
    objects don't have names. The object isn't aware of the xxx variable. Commented Aug 21, 2012 at 23:09

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

2 Comments

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: 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.