Apurv Singla
Apurv Singla

Reputation: 39

How can i call function chaining like without the use of the constructor(new) keyword?

i don't know how to call something like: let r = fun().func1(2).func2(2), without the use of new keyword. I know it via new keyword, something like let r = new fun().func1(2), but can I implement it with the syntax above.

Upvotes: 0

Views: 55

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386848

You could build a fluent interface by returning an object with the function, you need. To get a result, you need to specify a function which returns a value instead of an object, or implement a toString or valueOf function.

const
    fun = (result = 0) => {
        const functions = {
            add (value) {
                result += value;
                return functions;
            },
            multiply (value) {
                result *= value;
                return functions;
            },
            ans () {
                return result;
            }
        }

        return functions;
    };

console.log(fun().add(2).multiply(3).ans());

Upvotes: 1

user15388024
user15388024

Reputation:

Each function could return an object containing a function:

function fun() {
  return {func1(num1) {
    return {func2(num2) { 
      return num1 * num2;
    }}
  }}
}

let r = fun().func1(2).func2(2);
console.log(r);

Upvotes: 1

Related Questions