zoukankan      html  css  js  c++  java
  • JS

    柯里化是一种将使用多个参数的一个函数转换成一系列使用一个参数的函数的技术。

    思想:利用闭包的机制,把一些内容事先存储和处理了,等到后期需要的时候拿来即用即可

    需求:点击盒子后执行 fn 并把 this 指向 obj 

     由于 bind 不兼容 IE8 及以下,可以简单地用柯里化函数实现:

        let obj = {
                x: 100
            };
    
            function fn(y, ev) {
    // ev 代表事件对象
    this.x += y; console.log(this); } /* * bind:预先处理内容 * @params: * func:要执行的函数 * context:需要改变的 this 指向 * args:给函数传递的参数 * @return: * 返回一个代理函数 */ function bind(func,context,...args) { return function () { fn.call(context,...args) } }; box.onclick = bind(fn,obj,200); console.log();

    完整写法(把自己写的 bind 添加到 Function 原型上)

        (function(proto){
          function bind(context){
            context = context || window;
            let _this = this;
            let outerArgs = [].slice.call(arguments,1);
            return function proxy() {
              let innerArgs = [].slice.call(arguments,0);
              let args = outerArgs.concat(innerArgs);
              _this.apply(context,args);
            }
          }
          proto.bind = bind
        })(Function.prototype)

    可直接调用

    box.onclick = fn.bind(obj,200)
  • 相关阅读:
    C# 停止或开启服务
    微软企业库 缓存
    C# 获取图片一部分
    [转载]MVC3在win 2003虚拟主机上的调试
    mongodb查询的语法
    Mongodb亿级数据量的性能测试比较完整收藏一下
    正则验证数字
    收到了Gmail的Beta测试邀请
    C#新手经验点滴
    Windows消息机制
  • 原文地址:https://www.cnblogs.com/-xiao/p/12500489.html
Copyright © 2011-2022 走看看