return format.replace.call(this, /hh?|mm?/g, function(match)
format.replace
试着打电话
this.toString
,以无限递归结束。根据要求,以下是发生这种情况的证据:
http://jsbin.com/eweli/
:
var Quota = function(totalMinutes){
this.totalMinutes = parseInt(totalMinutes || 0, 10);
};
Quota.prototype.toString = function(format){
alert ("Quota.prototype.toString is called");
};
var q1 = new Quota(60);
var a = "string".replace.call(q1,'hello','world');
请尝试以下方法:
return format.replace(/hh?|mm?/g, function(match)
编辑
撇开问题不谈,我发现允许函数访问当前配额的最佳方法是在其闭包之外创建一个变量:
Quota.prototype.toString = function(format){
format = format || "hh:mm";
var quota = this;
return format.replace(/hh|mm/g, function(match){
switch (match) {
case "hh":
return quota.totalMinutes / 60;
case "mm":
return quota.totalMinutes;
}
return match;
});
};