gpt4 book ai didi

Javascript OOP - 返回函数中的函数

转载 作者:行者123 更新时间:2023-11-29 10:39:37 26 4
gpt4 key购买 nike

尝试创建仅在同一行中调用其他函数时才调用的函数调用。

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 不是函数

我做错了什么?

最佳答案

您需要在 this.done 函数的末尾返回 this 而不是 res 。通过返回 this,您将返回您的 this.done 函数,它是其中具有 percentage 函数的对象。

下面的代码运行没有错误:

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 this;
};
this.step = function() {
return 1 / (this.max - this.min);
};
}

processTrack.done(true, false).percentage();

关于Javascript OOP - 返回函数中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31485836/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com