1

如果我创建一个类SONG()并定义了许多属性,我如何创建一个使用传递的参数并获取该属性的方法?

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?

非常感谢任何帮助或建议!

4

2 回答 2

1

您可以使用方括号表示法:

this[title]

将获得标题变量中包含的名称的属性。

于 2013-02-06T14:56:58.523 回答
1

也许这就是你想要的:(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"));  

但请注意,我们是"title"作为字符串传入的。此外,需要在内部进行检查getstuff以验证SONG确实具有正在请求的属性,因此检查hasOwnProperty.

于 2013-02-06T14:59:03.437 回答