Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript auto-casting for numbers [duplicate]

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?

like image 850
Gershom Maes Avatar asked Oct 23 '25 03:10

Gershom Maes


1 Answers

You need to override valueOf:

Person.prototype.valueOf = function() {
    return this.age;
}

More info at MDN

like image 110
Matt Avatar answered Oct 25 '25 18:10

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!