实例化JavaScript的User类时控制台提示wolverine未定义问题求助
报错原因
- 你传入
new User的第二个参数wolverine、sabertooth没有添加引号包裹,JavaScript会默认将其识别为已声明的变量去作用域中查找,你没有提前定义过这两个变量,就会抛出「未定义」的报错。 - 对比你传入的第一个邮箱参数,用了单引号包裹,是合法的字符串类型值,不会触发变量查找逻辑。
修复方案
给两个姓名参数加上单/双引号,声明为字符串类型即可,修正后代码:
class User { constructor(email, name) { this.email = email; this.name = name; } } let userOne = new User('wolverine@marvel.com', 'wolverine'); let userTwo = new User('sabertooth@marvel.com', 'sabertooth'); console.log(userOne); console.log(userTwo);
修改后运行代码,控制台即可正常打印两个实例对象,包含对应的邮箱和姓名属性。
内容的提问来源于stack exchange,提问作者Chaz Carothers
相关产品推荐
相关产品推荐

