首页 > 解决方案 > 从另一个方法访问方法属性

问题描述

我想在另一个方法中访问一个类方法的属性,但我得到的是 NaN 结果。难道不能从 calSum() 访问 this.x 和 this.y 的值吗?谢谢

class Calc{
  constructor(){}
  
  num(){
    this.x = 5;
    this.y = 4;
  }
  
  calSum(){
    this.sum = this.x + this.y;
    console.log(this.sum);
  }
}

const s = new Calc();
s.calSum();

标签: javascript

解决方案


似乎this.xthis.y没有在Calc构造函数中初始化。

这导致this.xthis.yundefined

undefined + undefined产生NaN.

我已经更新constructor了 x 和 y 的初始值为零:

class Calc{
  constructor(){
    this.x = 0;
    this.y = 0;
  }
  
  num(){
    this.x = 5;
    this.y = 4;
  }
  
  calSum(){
    this.sum = this.x + this.y;
    console.log(this.sum);
  }
}

const s = new Calc();
s.calSum();

推荐阅读