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)
  • 相关阅读:
    lambda关键字
    11.4 传递函数:
    装饰器
    maven如何将本地jar安装到本地仓库
    揭秘:日赚千元的冷门暴利项目,这个产品99%的人不知道
    参数组
    你不知道的事:AWR 基线和 AWR Compare Period Report 功能介绍
    python 关键字和位置参数
    IDL 数组相关函数
    IDL 数组相关函数
  • 原文地址:https://www.cnblogs.com/-xiao/p/12500489.html
Copyright © 2011-2022 走看看