Given the following JavaScript “class” definition:
var Quota = function(totalMinutes){
this.totalMinutes = parseInt(totalMinutes || 0, 10);
};
Quota.prototype.valueOf = function(){
return this.totalMinutes;
};
Quota.prototype.toString = function(format){
format = format || "hh:mm";
return format.replace.call(this, /hh?|mm?/g, function(match){
switch (match) {
case "hh":
return this.totalMinutes * 60;
case "mm":
return this.totalMinutes;
}
});
};
Can you please explain exactly why the below call to toString()…
var q1 = new Quota(60);
console.log( q1.toString() );
…results in the following error being raised:
InternalError: too much recursion {
message=”too much recursion”,
more…}
I’m running the code (Firefox 3.5.7 + Firebug 1.5) in the Firebug Console. Ideally I’d like to know where is the recursive call back to toString() and your suggestions for how the replace function could be executed here via call or apply
format.replacetries to callthis.toString, which ends in an infinite recursion. As requested, here’s a proof this happens: http://jsbin.com/eweli/:Try this instead:
Edit
Problems aside, the best way I’ve found to allow the function to access the current quota is to create a variable outside it’s closure: