gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:32:44 35 4
gpt4 key购买 nike

我有很多类似于 FunctionOne 的函数。它们之间的区别是 Five = this.methodTwo(二,三,四,五)。我不想重复代码。为此,如何将函数的返回值作为参数传递?

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

最佳答案

解决这个问题的一种方法是将函数作为另一个参数。

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

关于javascript - 如何将函数的返回值作为参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58842024/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com