简体   繁体   English

如何在 ECMAScript 类中调用方法

[英]How the methods are called in ECMAScript class

 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}`);

I am getting consoled with valid output.我得到了有效输出的安慰。 But Unable to understand how the "toString" and "valueOf" methods are called here?但是无法理解此处如何调用“toString”和“valueOf”方法?

Any one help me to understand?有人帮我理解吗?

When you use console.log, or perform any operation that implicitly converts an object to a string, javascript will call toString() on that object, if that method is defined.当您使用 console.log 或执行任何将对象隐式转换为字符串的操作时,如果定义了该方法,javascript 将对该对象调用 toString()。

So this expression:所以这个表达式:

`${fivePercent}`

Tells javascript to get the value of fivePercent.toString() .告诉 javascript 获取fivePercent.toString()的值。

Likewise, when you evaluate this expression:同样,当您评估此表达式时:

50 * fivePercent

You're telling javascript to convert fivePercent to a numerical value, then multiply it by 50. If valueOf() is defined on the object, it will call that method to get the value;您告诉 javascript 将fivePercent转换为数值,然后将其乘以 50。如果在对象上定义了valueOf() ,它将调用该方法来获取值; otherwise, the result will be NaN.否则,结果将为 NaN。

JavaScript calls the valueOf method to convert an object to a primitive value. JavaScript 调用 valueOf 方法将对象转换为原始值。 It automatically invokes it when encountering an object where a primitive value is expected.当遇到需要原始值的对象时,它会自动调用它。

You can read more about it in the below link您可以在以下链接中阅读更多相关信息
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM