user7331530
user7331530

Reputation: 985

How can I pass function's return value as parameter?

I have lots of functions similar to FunctionOne. Difference in these is five = this.methodTwo(two, three, four, five). I don't want to repeat code. For doing that, how can I pass function's return value as parameter?

class MyClass {
    FunctionOne(one, two, three, four, five) {
        //some code here
        one = "my one";
        two = "my two";
        five = this.FunctionTwo(two, three, four, five); //How can I pass this as parameter
        one[five] = "something";
        return one;
    }
    FunctionThree(one, two, three, four, five) {
        //some code here
        one = "my one";
        two = "my two";
        five = this.FunctionFour(two, three, four, five); //Everything in FunctionThree is same as FunctionOne except this statement
        one[five] = "something";
        return one;
    }

    FunctionTwo(two, three, four, five) {
        //some code
        return five;
    }
}

Upvotes: 0

Views: 105

Answers (2)

Stephen P
Stephen P

Reputation: 14810

One way to approach this would be to take the function as another parameter.

Similar to your FunctionOne, FunctionTwo etc. you could have FunctionX which does the common work and calls the passed function which, as a parameter, can be varied by the caller.

That would look something like this:

// added 'fn', the function to call, as the sixth parameter
FunctionX(one, two, three, four, five, fn) {
    //some code here
    one = "my one";
    two = "my two";
    five = fn(two, three, four, five);
    one[five] = "something";
    return one;
}

Now you can call this elsewhere like:

let x = FunctionX(h, i, j, k, l, FunctionOne);

Upvotes: 1

Dmitri Algazin
Dmitri Algazin

Reputation: 3456

So,

  • By doing this:

    five = this.FunctionTwo(two, three, four, five)
    

you calling function 'FunctionTwo' with params (two, three, four, five) and assigning result of function 'FunctionTwo' to variable 'five'

  • By doing this:

    five = this.FunctionTwo
    

you are assigning function 'FunctionTwo' instance to variable 'five', but NOT calling it yet.

Basically later in the code you can do something like that:

five(two, three, four)
  • Not really clear what you want, but you can pass 'this' in to the 'FunctionTwo' and assign result to current object.

Ignore if nothing helps to you :)

Upvotes: 0

Related Questions