2

As you all know there is a toString() method for object which is called whenever the casting is required.

I was wondering if there is such a method for casting to number (like the Date object in which +new Date() returns the getTime() method's value).

For example (let's say there is toNumber method):

function MyObj(){}
MyObj.prototype.toNumber = function(){
    return 1362;
}
Nick
  • 95
  • 8

1 Answers1

3

Yes, it's called valueOf:

function MyObj(){}
MyObj.prototype.valueOf = function(){
    return 1362;
}

See also the second part of my answer here.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143