简体   繁体   中英

how to assign a value to a variable of a return function in javascript

I am trying to return a function that has an assigned variable in it. looking at the example code below:

function a(x){   
    function b(y){
        return x+y;
    }
    return b;
}

executing a(4) would return the function b in this format:

function b(y){
    return x+y;
}

now how can one make so executing a(4) returns b as below:

function b(y){
    return 4+y;
}

apologies for the title didn't know quite well how to word the question.

Since a(4) is what gives you b, you now need to call b(y). So if you wanted x to be 4 and y to be 5, you'd call:

a(4)(5) // returns 9

Assign the return value to another variable

 function a(x){ function b(y){ return x+y; } return b; } var add4 = a(4); console.log(add4(10)); var add6 = a(6); console.log(add6(15)); 

您的代码是正确的,使用方式是a(4)(3)。b中的x是a的参数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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