未定义对象

Not defined object

我正在尝试让我的对象在控制台中打印 wolverine 的电子邮件和姓名。但是,金刚狼在控制台中显示为“未定义”。当它是称为新用户的 class 的一部分时,这怎么可能?任何帮助将不胜感激。

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);

你得到 undefined(或者,在严格模式下,一个错误)因为变量 wolverinesabertooth 没有赋值,所以它们的值是......未定义。

您可能也希望将名称作为字符串传递:

let userOne = new User('wolverine@marvel.com', 'wolverine');
let userTwo = new User('sabertooth@marvel.com', 'sabertooth');

或者,您可能希望先将名称放入变量中,然后再将变量传入:

let nameOfGuyWithHandBlades = 'wolverine';
let totallyATiger = 'sabertooth';
let userOne = new User('wolverine@marvel.com', nameOfGuyWithHandBlades);
let userTwo = new User('sabertooth@marvel.com', totallyATiger);

这就是您将 wolverinesabertooth 作为变量而不是字符串传递的情况。

正确用法:

let userOne = new User('wolverine@marvel.com', 'wolverine');
let userTwo = new User('sabertooth@marvel.com', 'sabertooth');

像这样传递wolverine就把它当作一个变量,显然找不到它。

如果它是一个字符串,就像您对电子邮件所做的那样,您需要引号 '

let userOne = new User('wolverine@marvel.com', 'wolverine');
let userTwo = new User('sabertooth@marvel.com', 'sabertooth')