尝试创建一个函数调用,只有在同一行内已经调用了其他函数才能被调用。
var processTrack = new function() {
this.current = 1;
this.max = 5800;
this.min = 0;
this.done = function(started, processing, cur, len) {
cur = cur || 0;
len = len || 1;
var res = 0;
if (started && !processing)
res = ((this.current - 1 - this.min) / (this.max - this.min)).toFixed(2);
else if (!started && processing)
res = (this.done(true, false) + (this.step() * this.cur / this.len)).toFixed(2);
else if (!started && !processing)
res = ((++this.current - 1 - this.min) / (this.max - this.min)).toFixed(2);
this.percentage = function() {
return res * 100 + "%";
};
return res;
};
this.step = function() {
return 1 / (this.max - this.min);
};
}
我理想的情况是调用
processTrack.done(args).percentage()
方法从 .done(args)
返回的数据中获取百分比,但每当我尝试调用(例如)processTrack.done(true, false).percentage()
时,会出现以下错误:
TypeError: processTrack.done(...).percentage is not a function
我做错了什么?
res
上调用.percentage()
,而不是在this.done
上调用。尝试使用res.percentage = function() ...; return res;
来实现。 - David Ehrmannthis.done
必须返回this
,而不是res
。 - FélixprocessTrack = new function()
?你可以使用processTrack = function() {}
并在函数作用域内使用变量,只公开由函数返回的对象。 - Félix