【问题标题】:Javascript objects and methodJavascript对象和方法
【发布时间】:2017-11-26 15:10:08
【问题描述】:

请帮忙!我刚开始学习对象 ecc .. 我不想继续,因为我想真正了解 javascript 上的对象。所以我试着写了一个对象的代码,包括按小时支付、按周工作、费用、加班和 3 个功能。

var monthlyPay = {
//hours per week
     hourWeek: 40,
//pay per hours
     hourlyPay: 10,
//all the monthly expenses
     mothlyExpenses: 120,
//additional hours of work
     overtime: 7,

//function that calculates the bonus based on the overtime and hourlyPay plus 4
     calculateBonus: function(){
     this.Bonus = this.overtime * (this.hourlyPay + 4);
 },
//function that calculates the total monthly pay
     calculatePay: function(){
     this.Pay = this.hourWeek * this.hourlyPay + this.Bonus;
 },
//function that calcutes the remaining money
     calculateMoney: function(){
     this.Money = this.monthlyExpenses - this.Pay;
 },

};
monthlyPay.calculateMoney();
monthlyPay.calculateBonus();
monthlyPay.calculatePay();
console.log(monthlyPay);

它运行没有错误,但是当我查看浏览器控制台时,Money 属性的值为 NaN。提前感谢您的回答!

【问题讨论】:

  • 好吧,Money 取决于 Pay 的值,所以你必须先计算它。
  • this.Pay; 没有在任何地方定义。所以应该是NaN
  • 这篇文章可能会有所帮助:stackoverflow.com/a/47441358/1636522.
  • 你有一个拼写错误,你写的是 mothlyExpenses 而不是monthlyExpenses
  • 谢谢大家!!!我真的忘记了调用函数时重要的命令。

标签: javascript javascript-objects nan


【解决方案1】:

您的代码中有两个错误。
第一个是 Barden 提到的。
在其未定义的声明之前调用付款。

您还为变量声明拼错了monthlyExpenses。
因此:一个计算两个未定义的值也是未定义的。

尝试使用可用于 Money 的打印值进行调试:

calculateMoney: function(){
    console.log(`Params : \nmonthlyExpenses: ${this.monthlyExpenses} \nPay: ${this.Pay}`);
    this.Money = this.mothlyExpenses - this.Pay;
}
结果是:
参数:
每月费用:未定义
支付:未定义

总结一下:
1.改变函数调用顺序
2. 使monthlyExpenses 或mothlyExpenses 拼写相同

:)

【讨论】:

    【解决方案2】:

    总结说了什么:

    顺序应该是

    monthlyPay.calculateBonus();
    monthlyPay.calculatePay();
    monthlyPay.calculateMoney();
    console.log(monthlyPay);
    

    你应该写

    monthlyExpenses: 120,
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-01
      • 2013-08-17
      • 2021-12-14
      相关资源
      最近更新 更多