简体   繁体   中英

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?

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.

So this expression:

`${fivePercent}`

Tells javascript to get the value of 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; otherwise, the result will be NaN.

JavaScript calls the valueOf method to convert an object to a primitive value. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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