js学习六-闭包

闭包:
def:函数内部定义的子函数用到了父函数内部的变量,形成的特定作用域
功能:
1.保存函数的执行状态
code:
‘a1c2f3g4’中的数字依次用[‘b’.’d’,’e’,’h’]替换
//count变量会保存在闭包作用域内,表示func被调用的次数

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Closure1</title>
</head>
<body>
    <script type="text/javascript">
        var arr = ['b','d','e','h'];
        var str = 'a1c2f3g4';

        var func = (function() {
            var count = 0;
            return function() {
                return arr[count++];
            }
        })();

        str = str.replace(/\d/g, func);
        console.log(str);
        // abcdfegh

        //不使用闭包
        function sum(i, j) {
            var add = function (i, j) {
                return i+j;
            }
            return add(i, j);
        }
        var startTime = new Date();
        for(var i=0;i<1000000;i++) {
            sum(1, 1);
        }
        var endTime = new Date();
        console.log(endTime-startTime)
        //49

        //使用闭包
        var sum = (function () {
            var add = function(i, j){
                return i+j;
            }
            return function(i,j){
                add(i,j);
            }
        })()
        var startTime = new Date();
        for(var i=0;i<1000000;i++) {
            sum(1, 1);
        }
        var endTime = new Date();
        console.log(endTime-startTime)
        //4
    </script>
</body>
</html>

2.封装
私有变量,不被外部调用
3.性能优化
由于作用域的范围,节约了执行时间

first-class function(函数即变量):
功能如下:
1.函数可以当做参数
异步回调函数例如ajax
2.函数作为返回值
①Function.prototype.bind()此方法与function.apply(obj,param)方法类似
是指先绑定不作操作,如若执行则需要Function.prototype.bind()()
返回的是函数引用不是函数值
code:

var move = function (x,y) {
            this.x += x;
            this.y += y;
        };
        var p = {x:1,y:1};
        var pmove = move.bind(p,2,2);
        console.log(p)
        // Object {x: 1, y: 1}
        pmove();
        console.log(p)
        // Object {x: 3, y: 3}

②curry柯里化

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值