1

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.

4

1 回答 1

3

您在传递用户名属性名称时忘记了引号。传递的username参数必须是一个字符串 newUser.printInfo("username")

如果没有引号,它将尝试引用一个(不存在的)全局变量名为username.

请注意,您的printInfo函数将只返回属性的名称(与参数相同),而不是实际值。如果要返回用户名值,则必须以以下方式访问该键this[info]

    ...
    printInfo(info){
        if (info in this){
            return this[info];
        }
    }
于 2020-07-12T20:31:21.320 回答