javascript - 如何在 ECMAScript 类中调用方法
问题描述
class Percentage
{
constructor(percent)
{
this.percent = percent;
}
toString()
{
return `${this.percent}%`;
}
valueOf(){
return this.percent / 100;
}
}
let fivePercent = new Percentage(5);
console.log(`${fivePercent} of 50 is ${50*fivePercent}`);
我得到了有效输出的安慰。但是无法理解这里如何调用“toString”和“valueOf”方法?
任何人帮助我理解?
解决方案
当您使用 console.log 或执行任何将对象隐式转换为字符串的操作时,如果定义了该方法,javascript 将调用该对象的 toString()。
所以这个表达式:
`${fivePercent}`
告诉 javascript 获取fivePercent.toString()
.
同样,当您评估此表达式时:
50 * fivePercent
您是在告诉 javascript 转换fivePercent
为数值,然后将其乘以 50。如果valueOf()
在对象上定义,它将调用该方法来获取值;否则,结果将为 NaN。
推荐阅读
- javascript - node.js / javascript 应用程序是否支持 AES 密文窃取?
- discord - Discord py - 在“on_raw_reaction_add”函数中创建某个类别的频道?
- vb.net - 如何解析 XML 而不会对文件中的注释抛出异常
- javascript - 为什么我只在 Javascript 计算器中的减号运算符中看到 NaN?
- css - 如何降低标签的高度 - 棱角材料
- c++ - 如何旋转 AVFrame?
- typescript - 单击事件返回未定义。为什么?
- c# - SignalR Core 和接收消息
- storyboard - 在swift5中按下特定按钮时如何使用代码呈现tabBarViewController(在情节提要中创建)?
- markdown - Markdown/Hugo 帮助:如何定义一个包含项目符号的字符串?