在 JavaScript 中,如果函数接受一个或多个参数并返回一个需要剩余参数的新函数,则该函数被视为“柯里化”。柯里化是一种强大的技术,可用于从现有函数创建新函数,或“柯里化”深度为 n 的函数。
为什么我们要取消函数引用?
您可能想要uncurry某个函数的原因有多种。例如,您可能想要 -
如何取消函数引用?
使用“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” i> 方法作为单独的参数,而不是作为数组。例如 -
<!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”方法来取消函数引用有几个好处 -
总之,柯里化是一种强大的技术,可用于从现有函数创建新函数,或“柯里化”深度为 n 的函数。
以上就是如何在 JavaScript 中将函数递归到深度 n ?的详细内容,更多请关注编程之家其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。