我在阅读面向对象的 Javascript 并发现了闭包的概念。我不太明白为什么以及何时使用它。像 Java 这样的其他语言也有闭包吗?我基本上想了解了解闭包的概念如何帮助我改进编码。
最佳答案
闭包是具有绑定(bind)变量的第一类函数。
大致意思是:
- 您可以将闭包作为参数传递给其他函数
- 闭包存储了创建时存在的词法范围内的一些变量的值
Java 最初没有对闭包的语法支持(这些是在 Java 8 中引入的),尽管使用匿名内部类来模拟它们是相当普遍的做法。这是一个例子:
import java.util.Arrays;
import java.util.Comparator;
public class StupidComparator {
public static void main(String[] args) {
// this is a value used (bound) by the inner class
// note that it needs to be "final"
final int numberToCompareTo=10;
// this is an inner class that acts like a closure and uses one bound value
Comparator<Integer> comp=new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
int result=0;
if (a<numberToCompareTo) result=result-1;
if (b<numberToCompareTo) result=result+1;
return result;
}
};
Integer[] array=new Integer[] {1,10, 5 , 15, 6 , 20, 21, 3, 7};
// this is a function call that takes the inner class "closure" as a parameter
Arrays.sort(array,comp);
for (int i:array) System.out.println(i);
}
}
关于java - 什么是闭包? java有闭包吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3805474/