
在 JavaScript 中,如果函数接受一个或多个参数并返回一个需要剩余参数的新函数,则该函数被视为“柯里化”。柯里化是一种强大的技术,可用于从现有函数创建新函数,或“柯里化”深度为 n 的函数。
您可能想要uncurry某个函数的原因有多种。例如,您可能想要 -
在需要非柯里化函数的上下文中使用柯里化函数
将柯里化函数转换为非柯里化形式,使其更易于阅读或调试
立即学习“Java免费学习笔记(深入)”;
优化柯里化函数的性能
有两种方法对函数进行咖喱化 -
第一种方法是使用“Function.prototype.apply”方法。
第二种方法是使用“Function.prototype.call”方法。
“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" 方法也可用于将函数取消柯里化至深度 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”方法来取消函数引用有几个好处 -
“apply”方法比“call”方法更快。
“apply”方法比“call”方法得到更广泛的支持。
“apply”方法比“call”方法更简洁。
总之,柯里化是一种强大的技术,可用于从现有函数创建新函数,或“柯里化”深度为 n 的函数。
以上就是如何在 JavaScript 中将函数递归到深度 n ?的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号