javascript - 从另一个方法访问方法属性
问题描述
我想在另一个方法中访问一个类方法的属性,但我得到的是 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();
解决方案
似乎this.x
并this.y
没有在Calc
构造函数中初始化。
这导致this.x
和this.y
是undefined
。
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();
推荐阅读
- android - 收到通知且应用程序在后台时如何在android中调用另一个活动
- ios - Google AdMob iOS - 没有可显示的广告
- mysql - 将列从 int 转换为 varchar(32) 时 SQL 语法错误?
- arrays - excel使用返回数组的函数
- sql - bigquery 使用正则表达式连接表
- angular - 在 Angular 组件的其余部分之前完全加载订阅
- c# - 如何使用 Mutex 解决可能的竞争条件
- python - 为什么 win32api.SendMessage 不能在某些应用程序中执行鼠标点击
- php - 如何将 argv 与 file_get_contents 或 cURL 或类似的东西一起使用
- google-cloud-platform - Google Vision OCR,将文字坐标从 90、180、270 个文档旋转到 0 度