Javascript 面向对象编程 - 返回函数内的函数

3

尝试创建一个函数调用,只有在同一行内已经调用了其他函数才能被调用。

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

我做错了什么?


1
你试图在 res 上调用 .percentage(),而不是在 this.done 上调用。尝试使用 res.percentage = function() ...; return res; 来实现。 - David Ehrmann
1
this.done 必须返回 this,而不是 res - Félix
3
好的,重新考虑一下。你可能不想把演示逻辑放在跟踪进度的函数中。 - David Ehrmann
为什么要使用 processTrack = new function()?你可以使用 processTrack = function() {} 并在函数作用域内使用变量,只公开由函数返回的对象。 - Félix
2个回答

2
你需要在你的 this.done 函数结尾返回 this 而不是 res 。通过返回 this ,你返回的是拥有 percentage 方法的对象, 即this.done 函数所在的对象。
以下代码可以顺利运行:
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();

啊,原来是这个问题。谢谢。 - Confuseh

1

在done方法中返回这个。因为它返回的不是一个对象,而是res。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接