传递多个参数的闭包函数

closure function passing multiple arguments

本文关键字:闭包 函数 参数      更新时间:2023-09-26

我试图理解Javascript中的闭包。。我创建了一个函数并传递了2个值(a,b)。。我想知道内函数平方(x)是如何取a的值并在返回平方(a)+平方(b)之前返回其平方的。。

在案例2中,我做了类似的传递(x,y),但这不起作用。。

你能解释一下吗?

案例1

<html>
    <head>
        <script>
            function addsquares(a,b){
                function square(x){
                    return x * x;
                }
                return square(a) + square(b)
            }
            document.write(addsquares(2,3))
        </script>
    <head>
    <body>
    <body>
</html>

案例-2

<html>
    <head>
        <script>
            function addsquares(a,b){
                function square(x,y){
                    return x * y;
                }
                return square(a) + square(b)
            }
            document.write(addsquares(2,3))
        </script>
    <head>
    <body>
    <body>
</html>

所提供的代码中没有涉及闭包。内部函数立即执行,并从外部函数参数中传递适当的值。返回的是调用内部函数(两次,相加在一起)的结果,而不是闭包/函数对象!

否则,闭包的参数——这里是秘密:闭包只是在特定绑定上下文中创建的函数对象——就像普通函数一样。下面是一个实际上创建闭包的示例:

function multiply_over_sum(a){
    function sum(x, y) {
        return a * (x + y);
    }
    // NOW we create a closure - as a FUNCTION-OBJECT (sum)
    // is returned to the caller while maintaining access to the
    // current binding context.
    return sum;
}
// Then multiply_by5_over_sum is now a FUNCTION-OBJECT 
// that has "a" bound to the value 5.
// (It is a closure specifically because it binds to a variable.)
var multiply_by5_over_sum = multiply_over_sum(5);
// This FUNCTION-OBJECT (closure) can be INVOKED like any function
// to yield a value. In this case the values 4 and 3 are passed as
// the arguments for "x" and "y", respectively
var sum = multiply_by5_over_sum(4, 3);

虽然这不是严格正确的(因为闭包绑定到JavaScript中的变量,而不是),但上面给出的例子中的闭包可以看作以下函数:

var multiply_by5_over_sum = function (x, y) {
  return 5 * (x + y);
};

也就是说,只捕获了闭包中绑定的变量("a")。参数"x"answers"y"只是闭包/函数的参数,并且只有在调用闭包时才会绑定到值,就像multiply_by5_over_sum(4, 3)所做的那样。