class User{
constructor(username,description){
this.username = username
this.description = description
}
printInfo(info){
if (info in this){
return info
}
}
}
let newUser = new User("testUsername","testDescription")
newUser.printInfo(username)
当我尝试此操作时,它在的第17行给了我一个错误Uncaught ReferenceError
。
传递用户名属性名称时,您忘记了引号。传递的username
参数必须是字符串 newUser.printInfo("username")
。
如果没有引号,它将尝试引用名为的(不存在)全局变量username
。
请注意,您的printInfo
函数只会返回属性的名称(与参数相同),而不是实际值。如果要返回用户名值,则必须以以下方式访问该键this[info]
:
...
printInfo(info){
if (info in this){
return this[info];
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句