I'm aware of how to control the way any object casts to String in javascript:
var Person = function(firstName, lastName, age, heightInCm) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.heightInCm.heightInCm;
};
Person.prototype.toString = function() {
return this.firstName + ' ' + this.lastName;
};
var friend = new Person('Bob', 'Johnson', 41, 183);
// Will automatically treat `friend` as a string using `Person.prototype.toString`
console.log(`Meet my friend ${friend}. He's SUPER AWESOME!!`);
As you can see, friend is auto-casted to String. My question is: does this same functionality exist for numbers?
I can see that String instances are capable of auto-casting to Number:
>>> 5 * '5'
25
But I'm not sure how to implement this automatic conversion on custom objects. The following does not work:
Person.prototype.toNumber = function() {
return this.age;
};
console.log(friend * 2); // Intended to be 82, but the result is NaN
How do I allow a custom object to automatically cast to a number?
You need to override valueOf:
Person.prototype.valueOf = function() {
return this.age;
}
More info at MDN
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With