尝试实现构造函数模式的JavaScript

时间:2019-03-07 16:05:47

标签: javascript

即使填充了值,我也得到了不确定的值。我想我已经填充了它,但是感觉对象实例出了点问题。如果有人可以解释我要去哪里错,那就太好了。

function Student(fn, sn, a, d)
{
  this.firstName = fn;
  this.lastName = sn;
  this.age = a;
  this.degree = d;
  this.displayStudent = displayStudent;
}

function displayStudent()
{
  console.log(this.fn);
  console.log(this.sn);
  console.log(this.a);
  console.log(this.d);
}

var studentObj = new Student("d", "r", 20,
                         "bachelors of science");
studentObj.displayStudent();

2 个答案:

答案 0 :(得分:1)

我认为这只是一个错字,您的代码应如下所示:

function Student(fn, sn, a, d)
{
  this.firstName = fn;
  this.lastName = sn;
  this.age = a;
  this.degree = d;
  this.displayStudent = displayStudent;
}

function displayStudent()
{
  console.log(this.firstName);
  console.log(this.lastName);
  console.log(this.age);
  console.log(this.degree);
}

var studentObj = new Student("d", "r", 20,
                         "bachelors of science");
studentObj.displayStudent();

在代码中,您尝试打印Student的“构造函数”属性,而不是设置的Student的“对象”参数。

答案 1 :(得分:1)

您正在尝试显示Student构造函数参数 除了显示学生属性以外,在构造函数外部声明的方法无法访问构造函数的参数。要使用displayStudents()方法显示学生属性,请执行以下操作。

function Student(fn, sn, a, d)
{
  this.firstName = fn;
  this.lastName = sn;
  this.age = a;
  this.degree = d;
  this.displayStudent = displayStudent;
}

function displayStudent()
{
  console.log(this.firstName);
  console.log(this.lastName);
  console.log(this.age);
  console.log(this.degree);
}

var studentObj = new Student("d", "r", 20,
                         "bachelors of science");
studentObj.displayStudent();

此外,当您在对象构造函数之外声明方法时,应使用此类的prototype属性。

function Student(fn, sn, a, d)
{
  this.firstName = fn;
  this.lastName = sn;
  this.age = a;
  this.degree = d;
}

Student.prototype.displayStudent = function()
{
  console.log(this.firstName);
  console.log(this.lastName);
  console.log(this.age);
  console.log(this.degree);
}

var studentObj = new Student("d", "r", 20,
                         "bachelors of science");
studentObj.displayStudent();