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 bob = new Person('Bob', 'Johnson', 41, 183);
// Will automatically treat `bob` as a string using `Person.prototype.toString`
console.log('Meet my friend ' + bob + '. 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(bob * 2); // Intended to be 82, but the result is NaN
How do I allow a custom object to automatically cast to a number?