首页 > 解决方案 > 如何在 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”方法?

任何人帮助我理解?

标签: javascriptecmascript-6

解决方案


当您使用 console.log 或执行任何将对象隐式转换为字符串的操作时,如果定义了该方法,javascript 将调用该对象的 toString()。

所以这个表达式:

`${fivePercent}`

告诉 javascript 获取fivePercent.toString().

同样,当您评估此表达式时:

50 * fivePercent

您是在告诉 javascript 转换fivePercent为数值,然后将其乘以 50。如果valueOf()在对象上定义,它将调用该方法来获取值;否则,结果将为 NaN。


推荐阅读