【问题标题】:JavaScript output from constructor function comes back as 'undefined'构造函数的 JavaScript 输出返回为“未定义”
【发布时间】:2016-11-15 07:48:12
【问题描述】:

当我将参数传递给console.log() 内部的setGear() 时,结果返回undefined,这是为什么呢?结果应该是我传入的数字。

var Bike = function() {
  var gear = 2;                     // private var set to an arbitrary number

  this.setGear = function(change) { // public method
    gear = change;
  };

  this.getGear = function() {       // public method
    return gear;
  };
};

var myBike = new Bike();

console.log(myBike.setGear(4)); // returns undefined, should return 4
console.log(myBike.setGear(3)); // returns undefined, should return 3
console.log(myBike.setGear(1)); // returns undefined, should return 1

【问题讨论】:

  • setGear 不返回任何内容,因此undefined 是默认返回值。
  • setter 不应该返回任何东西,getter 应该...
  • @epascarello --- 完全正确!也许我应该在发帖之前说清楚,我的问题不会被否决。此代码来自 Free Code Camp 练习,该练习旨在说明构造函数。我看不出从getGear() 返回的意义,但这就是他们提供的。我只是想在 node.js 中查看结果。
  • 所以添加退货或致电myBike.getGear()
  • @epascarello --- 我只是想让它以提供代码的方式工作。我现在看到他们的例子是一个坏例子,我希望我能在与之抗争之前看到这一点,然后花时间发布我的问题。我只是想把它留在那里,但感谢您的意见,它有所帮助。

标签: javascript constructor return private public


【解决方案1】:
this.setGear = function(change) { // public method
  gear = change;
};

不应返回 4。

this.setGear = function(change) { // public method
  gear = change;
  return gear;
};

应该这样做

【讨论】:

    【解决方案2】:

    如果你设置了 myBike.setGear,你应该调用 myBike.getGear 函数返回齿轮; myBike.setGear(4); console.log(myBike.getGear);

    【讨论】:

      猜你喜欢
      • 2021-03-17
      • 2021-12-21
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-07
      • 1970-01-01
      相关资源
      最近更新 更多