在javascript OOP中使用方法动态获取属性
如果我创建了一个类在javascript OOP中使用方法动态获取属性,javascript,oop,Javascript,Oop,如果我创建了一个类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]
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?
非常感谢您的任何帮助或建议 您可以使用方括号表示法:
this[title]
将使用title变量中包含的名称获取属性。可能这就是您想要的:()
但请注意,这里我们将以字符串形式传递
“title”
。此外,还需要在getstuff
中进行检查,以验证SONG
是否确实具有所请求的属性,因此检查hasOwnProperty
,这是因为您的内部this.stuff
是指其内部的annon函数。请注意song1.getstuff(title)
尝试将变量title
(未定义)传递给getstuff
@ryan:因为对象没有属性stuff
,这个。stuff
只是未定义的。嘿,谢谢你的回复,我不确定我将它放在哪里。我在函数中有这个[title]
你的函数代码在哪里?没关系,这很有效!我想我没有把参数作为字符串传递。谢谢谢谢我想我没有像你说的那样把论点当作字符串传递。
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"));