1

If I create a class SONG(), and define many properties, how can i create a method that will use an argument passed through and get that property?

function SONG(i) {

    /* properties */
    this.title      = results.title[i];
    this.artist     = results.artist[i];
    this.album      = results.album[i];
    this.info       = results.info[i];

    /* methods */
    this.getstuff = function(stuff){
        console.log(this.stuff); // doesn't work
    }
}

var song1 = new SONG(1);

song1.getstuff(title);  
// how can I have this dynamically 'get' the property passed through as an argument?

any help or advice is greatly appreciated!

d-_-b
  • 21,536
  • 40
  • 150
  • 256

2 Answers2

1

You can use square-bracket notation:

this[title]

will get the property with the name contained in the title variable.

Levi Botelho
  • 24,626
  • 5
  • 61
  • 96
1

Maybe this is what you want: (JSFiddle)

function SONG(i) {
    /* properties */
    this.title      = "My Title";
    this.artist     = "My Artist";
    /* methods */
    this.getstuff = function(stuff){
        if (this.hasOwnProperty(stuff))
            return this[stuff];
        else
            return null;
    }
}

var song1 = new SONG(1);

console.log(song1.getstuff("title"));  
console.log(song1.getstuff("invalid"));  

But notice here that we are passing in "title" as a string. Also, there needs to be a check within getstuff to validate that SONG indeed has the property that is being requested, hence the check for hasOwnProperty.

Hari Pachuveetil
  • 10,294
  • 3
  • 45
  • 68