对象的原型方法仅返回函数定义,而不执行。

时间:2018-11-28 15:32:58

标签: javascript oop

我正在审查创建和“实例化”对象的原型方法,但遇到了问题。当我输入以下代码到浏览器的控制台中进行测试时,如果输入:

nUser1.myAge()  // only the function definition is returned, doesn't actually execute.

我认为也许我需要在该方法上使用return语句,但这没什么区别。另外,在我先前的(成功的)练习尝试中,他们不需要return语句即可返回相应方法的输出。

我已经遍历了几次代码,并将其与其他示例进行了比较,但没有什么比这更好。我觉得问题出在我的鼻子底下,但我没有看到。

function normUserCreator(name, age, employed) {
  this.name = name;
  this.age = age;
  this.employed = employed;
};

normUserCreator.prototype.myName = function() {
  console.log("My name is: " + this.name + ".")
};
normUserCreator.prototype.myAge = function() {
  console.log("My age is : " + this.myAge + ".")
};
normUserCreator.prototype.employed = function() {
  if (this.employed === true) {
    console.log("I am employed");
  } else if (this.employed === false) {
    console.log("I am not employed");
  }
};

var nUser1 = new normUserCreator('Kevin', 26, false);

1 个答案:

答案 0 :(得分:3)

错误在这一行

console.log("My age is : " + this.myAge + ".")

它基本上是自称。用this.age

替换

此外,您可以将if (this.employed === true)的条件if (this.employed)替换为else if

function normUserCreator(name, age, employed) {
  this.name = name;
  this.age = age;
  this.employed = employed;
};

normUserCreator.prototype.myName = function() {
  console.log("My name is: " + this.name + ".")
};
normUserCreator.prototype.myAge = function() {
  console.log("My age is : " + this.age + ".")
};
normUserCreator.prototype.employed = function() {
  if (this.employed) {
    console.log("I am employed");
  } else if (!this.employed) {
    console.log("I am not employed");
  }
};

var nUser1 = new normUserCreator('Kevin', 26, false);
nUser1.myAge()