如何在 JavaScript 中将函数取消柯里化至深度 n?

front end technologyjavascriptweb development

在 JavaScript 中,如果函数接受一个或多个参数并返回一个需要其余参数的新函数,则该函数被视为"柯里化"。柯里化是一种强大的技术,可用于从现有函数创建新函数,或将函数"取消柯里化"至深度 n。

我们为什么要取消柯里化函数?

您可能想要取消柯里化函数的原因有多种。例如,您可能想要 −

  • 在需要非柯里化函数的上下文中使用柯里化函数

  • 将柯里化函数转换为非柯里化形式,使其更易于阅读或调试

  • 优化柯里化函数以提高性能

如何取消柯里化函数?

有两种方法可以取消柯里化函数 −

  • 第一种方法是使用"Function.prototype.apply"方法。

  • 第二种方法是使用"Function.prototype.call"方法。

使用"Function.prototype.apply"方法

"Function.prototype.apply" 方法可用于反柯里化 函数,深度可达 n。为此,只需将"this"值和参数数组传递给 "apply" 方法即可。例如 −

<!doctype html> <html> <head> <title>Examples</title> </head> <body> <p>uncurry up to depth 2 using Function apply() method</p> <div id="result"></div> <script> function add(a, b) { return a + b; } function curriedAdd(a) { return function(b) { return a + b; } } // Uncurry the "curriedAdd" function up to depth 2: document.getElementById("result").innerHTML = curriedAdd.apply(null, [1]).apply(null, [2]); // 3 </script> </body> </html>

使用"Function.prototype.call"方法

"Function.prototype.call"方法也可用于将函数反柯里化至深度 n。"call"方法类似于"apply"方法,但您将"this"值和参数作为单独的参数而不是数组传递给"call"方法。例如 -

<!doctype html> <html> <head> <title>Examples</title> </head> <body> <p> uncurry up to depth 2 using Function call() method</p> <div id="result"></div> <script> function add(a, b) { return a + b; } function curriedAdd(a) { return function(b) { return parseInt(a) + parseInt(b); } } // Uncurry the "curriedAdd" function up to depth 2: document.getElementById("result").innerHTML = curriedAdd.call(null, [1]).call(null, [2]); // 3 </script> </body> </html>

在上面的例子中,我们使用了 "call" 方法来取消对 "curriedAdd" 函数的柯里化。如您所见,"call"方法比"apply"方法更冗长,但效果相同。

使用"Function.prototype.apply"方法有什么好处?

使用"Function.prototype.apply"方法取消柯里化函数有几个好处 -

  • "apply"方法比"call"方法更快。

  • "apply"方法比"call"方法得到更广泛的支持。

  • "apply"方法比"call"方法更简洁。

总之,柯里化是一种强大的技术,可用于从现有函数创建新函数或"取消柯里化"函数直至深度


相关文章