javascript - 尝试在类中创建属性然后设置它们的值

标签 javascript

我以为我做对了,但错误是:

失败的测试:

Should be a class with name, email, and password properties. Expected undefined to be 'Dan'.

我查看了 MDN 和 w3schools,但显然,我只是不理解它。不过我知道我很接近。

function ClassOne(name, pw, mail){
   /*Exercise One: In this exercise, you will be creating your own class!
   You are currently in the class, you are given three strings, name, pw, and mail.
   You need to create three properties on this class.
   Those properties are: 'username', 'password', and 'email'
   Set the value of username to name,
   Set the value of password to pw,
   Set the value of email to mail */
    }
  function User(username, password, email) {
      this.username = 'name';                 //<-------My Code
      this.password = 'pw';                   //<-------My Code
      this.email = 'mail';                    //<-------My Code
  }
 const dan = new User ('Dan', '123xyz', 'dan@aol.com');          //<-------My Code

最佳答案

您需要将属性设置为等于您传递给构造函数的参数。现在您正在将值传递给构造函数,但不使用它们。一旦进入构造函数,您就可以将属性值设置为文字字符串。像这样尝试:

function ClassOne(username, password, email) {
  this.username = username;
  this.password = password;
  this.email = email;
}
const dan = new ClassOne('Dan', '123xyz', 'dan@aol.com');

console.log(dan);

关于javascript - 尝试在类中创建属性然后设置它们的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55050017/

相关文章:

javascript - 悬停显示数据的 Canvas 图表

javascript - Vee-Validate 仅验证一个字段

javascript - 如何让我的函数被 $(..).name() 调用?

javascript - 什么时候会无法确定 let 或 const 是否已初始化?

javascript - 是否存在特定内容的div

javascript - 如何在 Meteorjs 中提交隐藏输入的值

javascript - D3 分区 - 单击时显示下一个级别

javascript - 尝试使用 Karma/Jasmine 测试 Angular,但无法让 Jasmine 测试正确设置 $scope

javascript - Jquery 将 onClick 函数作为单独的函数运行

javascript 替换源标签内的代码