如何在javascript中使用函数(1)(2)?它是如何工作的? [英] how to use function(1)(2) in javascript? and how does it work?

查看:127
本文介绍了如何在javascript中使用函数(1)(2)?它是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解调用函数(1)但不是函数(1)(2),它是如何工作的?



也可以用于函数(1)(2)(3)(4)吗?

解决方案

在这种情况下,你假设函数(1)返回一个函数,而不是你调用这个新的匿名函数,其参数为2。

 函数sum(a){
返回函数(b){
返回a + b;
}
}

//用法:
window.alert(sum(5)(3)); //显示8

var add2 = sum(2);
window.alert(add2(5)); //显示7
window.alert(typeof(add2)); //显示'函数'

这里我们创建一个函数 sum 需要一个参数。在函数 sum 中,我们创建了一个带有另一个参数的匿名函数。这个匿名函数是作为执行 sum 的结果返回的。



请注意,这个匿名函数是我们称之为 封闭 。闭包是一个函数,它保持创建它的上下文。在这种情况下,它将保持变量 a 的值,就像示例函数 add2 一样。如果我们创建了很多闭包,它们就像你看到的那样是独立的:

  var add3 = sum(3); 
var add4 = sum(4);

window.alert(add3(3)); //显示6
window.alert(add4(3)); //显示7

另外,如果您有类似命名的局部变量,它们不会混淆 :

  var a =Hello,world; 

函数乘法(a){
返回函数(b){
return a * b;
}
}

window.alert(multiply(6)(7)); //显示42

var twoTimes = multiply(2);
window.alert(typeof(twoTimes));
window.alert(twoTimes(5));

因此,在调用 sum(2) multiply(2)结果不是数字,也不是字符串,而是函数。这是 功能性语言 的一个特征 - 语言中的功能可以作为参数传递并作为其他函数的结果返回。


I understand calling function(1) but not function(1)(2), how does it work?

also possible for function(1)(2)(3)(4) too?

解决方案

In this case you are supposing that function(1) returns a function, than you are calling this new, anonymous function with an argument of 2.

See this example:

function sum(a) {
    return function(b) {
        return a+b;
    }
}

// Usage:
window.alert(sum(5)(3));         // shows 8

var add2 = sum(2);
window.alert(add2(5));           // shows 7
window.alert(typeof(add2));      // shows 'function'

Here we create a function sum that takes one argument. Inside the function sum, we create an anonymous function that takes another argument. This anonymous function is returned as the result of executing sum.

Note that this anonymous function is a great example of what we call closure. A closure is a function that keeps the context in which it was created. In this case, it will keep the value of the variable a inside it, as did the example function add2. If we create many closures, they are independent as you can see:

var add3 = sum(3);
var add4 = sum(4);

window.alert(add3(3)); // shows 6
window.alert(add4(3)); // shows 7

Furthermore, they won't get "confused" if you have similarly named local variables:

var a = "Hello, world";

function multiply(a) {
    return function(b) {
        return a * b;
    }
}

window.alert(multiply(6)(7)); // shows 42

var twoTimes = multiply(2);
window.alert(typeof(twoTimes));
window.alert(twoTimes(5));

So, after a call to sum(2) or multiply(2) the result is not a number, nor a string, but is a function. This is a characteristic of functional languages -- languages in which functions can be passed as parameters and returned as results of other functions.

这篇关于如何在javascript中使用函数(1)(2)?它是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆