Javascript OOP - function in return function

Attempting to create a function call that only gets called when another function is called within the same line.

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);
    };
}

      

Ideally, I want to call processTrack.done(args).percentage()

to get the percentage of data received from .done(args)

, but whenever I try to call (for example) processTrack.done(true, false).percentage()

it gives me an error:

TypeError: processTrack.done(...).percentage is not a function

What am I doing wrong?

+3


source to share


2 answers


You need to return this

instead res

at the end of your function this.done

. By this

returning, you are returning your function this.done

, which is an object that has a function in it percentage

.

The following code works without error:



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();

      

+2


source


Return this to the prepared method. Since it returns res which is not an object



+1


source







All Articles