如何传递函数的返回值作为参数?

时间:2019-11-13 16:58:48

标签: javascript

我有很多类似于FunctionOne的功能。它们之间的区别是five = this.methodTwo(two, three, four, five)。我不想重复代码。为此,如何传递函数的返回值作为参数?

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

2 个答案:

答案 0 :(得分:1)

一种解决方法是将 function 作为另一个参数。

类似于您的FunctionOne,FunctionTwo等,您可以使用FunctionX来完成共同的工作并调用传递的函数,该函数作为参数可以被调用者改变。

这看起来像这样:

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

现在您可以在其他地方调用此名称,

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

答案 1 :(得分:0)

所以

  • 这样做:

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

调用带有参数(两个,三个,四个,五个)的函数'FunctionTwo'并将函数'FunctionTwo'的结果分配给变量'five'

  • 这样做:

    five = this.FunctionTwo
    

您正在将函数'FunctionTwo'实例分配给变量'five',但尚未调用它。

基本上,稍后在代码中,您可以执行以下操作:

five(two, three, four)
  • 不是很清楚您想要什么,但是您可以将'this'传递给'FunctionTwo'并将结果分配给当前对象。

如果有什么对您有用的,请忽略:)