Skip to content Skip to sidebar Skip to footer

Getting Object Name From Inside The Class (JavaScript)

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

Solution 1:

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/


Post a Comment for "Getting Object Name From Inside The Class (JavaScript)"