简体   繁体   English

javascript中的cururing功能

[英]Currying function work in javascript

Can someone please explain the below 'Currying' function. 有人可以解释下面的“整理”功能吗? When I set a break point, I can see values 'b' and 'c' are undefined and returned. 设置断点时,可以看到未定义并返回值“ b”和“ c”。 But how does the system get the value 7 for 'b' and 9 for 'c' in this case. 但是在这种情况下,系统如何获得'b'的值7和'c'的值9。 Its printing the correct result for 5*7*9, ie 315 in console. 它为5 * 7 * 9打印正确的结果,即在控制台中为315。

function multiply(a){
    return function (b){
        return function (c) {       
            return a*b*c ;
                }
        }
    }
var answer = multiply(5)(7)(9);
console.log(answer);

When you call multiply(5) a function is returned and that function is immediately called with multiply(5)(7) and have access to a and b , then a new function is returned and is also immediately called when multiply(5)(7)(9) and has access to a , b , and c . 当您调用multiply(5)将返回一个函数,并且该函数将立即被multiply(5)(7)调用,并且可以访问ab ,然后将返回一个新函数,并且在multiply(5)(7)(9)并可以访问abc

The answer to why the nested functions have access to parent function parameters is closures . 为什么嵌套函数可以访问父函数参数的答案是闭包 Please check this other question/answers about closures in javascript: link . 请在javascript: link中检查有关闭包的其他问题/答案。

You can understand currying if you assign each intermediate result to a variable. 如果将每个中间结果分配给变量,则可以理解currying。 Rewrite the function calls like this: 像这样重写函数调用:

var x = multiply(5)
var y = x(7);
var answer = y(9);

Now it is more clear that the result of calling multiply(5) is a function. 现在更加清楚的是,调用multiply(5)的结果是一个函数。 We call it with x(7) which passes the value of 7 to b . 我们用称之为x(7)其传递的值7b This results in another function which we call with y(9) which in turn passes the value of 9 to c and returns the final result. 这导致另一个函数,我们用y(9)调用该函数,然后将9的值传递给c并返回最终结果。

When you call the multiply function, the important thing is each function returns an anonymous function. 调用乘法函数时,重要的是每个函数都返回一个匿名函数。 It will be easier if you give them names. 如果给他们起名字会更容易。

function multiplyA(a){
    return function multiplyB(b){
        return function multiplyC(c) {       
            return a*b*c ;
        }
    }
}

// When you call multiplyA(5)(7)(9)
// From the first, multiplyA(5) returns multiplyB with scope with multiplyA
// just like below

const a = 5;
const multiplyB = function(b){
    return function multiplyC(c) {       
        return a*b*c ;
    }
}

// Once more call multiplyB(7)
// It also returns function named multiplyC

const a = 5;
const b = 7;
const multiplyC = function(c) {
    return a * b * c;
}

// Finally call mulitplyC(9) means 5 * 7 * 9

To understand it, closure and function scope will be helpful. 要理解它,闭包和函数范围将很有帮助。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Closures

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM