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 = newMyClass( 'xxx' );

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

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

var myHash = {};

varMyClass = function( name ) {
    if( !name ) throw'name is required';
    this.name = name;
    myHash[ name ] = this;
    returnthis;
};
//add static helperMyClass.create = function( name ) {
    newMyClass( name );
};    

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

//access itconsole.log( myHash.xxx )​;

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

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