闭包简单实现

        //统计函数调用次数
        function count(){
            let i = 0
            function fn(){
                i++
                console.log(`函数被调用了${i}次`)
            }
            return fn
        }
        const fun = count()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在 Java 中实现闭包可以使用匿名内部类和 lambda 表达式。 1. 使用匿名内部类实现闭包: ```java public class ClosureDemo { public static void main(String[] args) { Closure closure = new Closure(); int a = 10; int b = 5; int result = closure.operate(a, b, new Operation() { @Override public int operate(int a, int b) { return a + b; } }); System.out.println(result); // 15 } } interface Operation { int operate(int a, int b); } class Closure { public int operate(int a, int b, Operation operation) { return operation.operate(a, b); } } ``` 在上述代码中,我们定义了一个 `Closure` 类,该类有一个 `operate` 方法,该方法接受三个参数:两个整数和一个 `Operation` 接口的实例。`Operation` 接口定义了一个 `operate` 方法,该方法接受两个整数并返回一个整数。 在 `main` 方法中,我们实例化了一个 `Closure` 对象,并传递了两个整数和一个匿名内部类作为 `Operation` 接口的实现。在匿名内部类中,我们实现了 `operate` 方法,将两个整数相加并返回结果。 2. 使用 lambda 表达式实现闭包: ```java public class ClosureDemo { public static void main(String[] args) { Closure closure = new Closure(); int a = 10; int b = 5; int result = closure.operate(a, b, (x, y) -> x + y); System.out.println(result); // 15 } } interface Operation { int operate(int a, int b); } class Closure { public int operate(int a, int b, Operation operation) { return operation.operate(a, b); } } ``` 在上述代码中,我们使用 lambda 表达式实现了 `Operation` 接口的 `operate` 方法。在 `main` 方法中,我们实例化了一个 `Closure` 对象,并传递了两个整数和一个 lambda 表达式作为 `Operation` 接口的实现。lambda 表达式中,我们将两个整数相加并返回结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值