Skip to content Skip to sidebar Skip to footer

Set A Number Return Value For An Object

I've previously asked a fairly similar question, and with this answer, I know it's possible to make objects that return strings when placed inside other strings. This would be some

Solution 1:

I believe the prototype method you are looking for that handles object to numeric conversion is Object.prototype.valueOf()

It can be altered or customized just as you are altering toString()

Be aware that this sort of thing can be considered bad style when it may confuse other programmers (including yourself at a future date) as standard conversions can be redefined to behave differently than expected.

Solution 2:

toString is the method that is invoked when an object is used in a string context (more exactly, when ToString is called on it). And yes, there is a similar method that is invoked when an objet is used in a numeric context (ToNumber): valueOf. If either doesn't exist, the other is used, for details see the DefaultValue algorithm.

functionMyHybrid(str, num) {
    this.string = str;
    this.value = num;
}
MyHybrid.prototype.toString = function() {
    returnthis.string;
};
MyHybrid.prototype.valueOf = function() {
    returnthis.value;
};

var hybrid = newMyHybrid('Foo', 42)
String(hybrid) // "Foo"Number(hybrid) // 42

However, it must be noted that strObj+'', which you have used for a conversion into a string, does not call ToString. The + operator can both act on numbers and strings, and therefore does only call ToPrimitive without a type hint - in which case valueOf is preferred (unless it is a Date object). hybrid+'' is equivalent to 42+'' and will yield "42".

Post a Comment for "Set A Number Return Value For An Object"