给出以下JavaScript"类"定义:
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;
}
});
};
Run Code Online (Sandbox Code Playgroud)
你能否详细解释下面为什么打电话给toString()......
var q1 = new Quota(60);
console.log( q1.toString() );
Run Code Online (Sandbox Code Playgroud)
...导致出现以下错误:
InternalError:过多的递归{message ="过多的递归",更多...}
我在Firebug控制台中运行代码(Firefox 3.5.7 + Firebug 1.5).理想情况下,我想知道递归回调的位置toString()以及关于如何通过call或执行替换功能的建议apply
return format.replace.call(this, /hh?|mm?/g, function(match)
Run Code Online (Sandbox Code Playgroud)
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');
Run Code Online (Sandbox Code Playgroud)
试试这个:
return format.replace(/hh?|mm?/g, function(match)
Run Code Online (Sandbox Code Playgroud)
抛开问题,我发现允许函数访问当前配额的最好方法是在它的闭包之外创建一个变量:
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;
});
};
Run Code Online (Sandbox Code Playgroud)