zoukankan      html  css  js  c++  java
  • call、apply、bind函数的理解以及手写。

    理解

    1、相同点,这三个是一个函数。函数。函数。都可以改变函数的this指向 第一个参数都是this要指向的对象。例如

    var obj = {
        name:"lucy"
    }
    function FunCall(a,b,c){
        console.log(this.name); //lucy 
        console.log("参数",a,b,c) // a b c
    }
    FunCall.call(obj,'a','b','c')

     2、不同点:1、call接受的第二个参数,甚至可以接收是多个参数,2、apply,第二个参数是一个数组。 3、bind ,方法返回一个新的函数。

    手写实现

    call函数

    特点: 

    1、可以改变当前函数的this指向(就是改变函数的调用者)。2、还会让当前函数执行

    // 1、将方法挂载到我们传入的要绑定this的对象上,2,将挂载后的方法调用,3,将添加的方法属性删除
    Function.prototype.mycall = function(thisArg, ...args) {
        // thisArg代表this当前所需要指向的对象,args表示该函数接收的参数。
        const fn = Symbol('fn');// 创建一个变量,使用Symbol是因为保证他的唯一性。不被thisArg其他相同fn属性覆盖。
        const thisArg = thisArg || window;
        thisArg[fn] = this;// 这个this代表的是调用call方法的函数,比如foo.call(),this代表foo函数,  (改变函数的调用者,)
        const result =  thisArg[fn](...args);  // (让当前函数执行)
        delete thisArg[fn];
        return result;
    }

    2、手写apply的方法和手写bind的方法类似

     Function.prototype.myapplay = function(obj, args = []){
        if(Array.isArray(args)){
            throw ('需要传入数组')
        }
        const fn = Symbol('fn');
        const obj = obj || window;
        obj[fn] = this;
        const result = obj[fn](...args);
        delete obj[fn];
        return result;
    }

    3、手写bind

    • 特点
      • 绑定this指向
      • 返回一个绑定后的函数(高阶函数原理)
      • 如果绑定的函数被new执行 ,当前函数的this就是当前的实例
      • new出来的结果可以找到原有类的原型
    Function.prototype.mybind = function(obj, ...args1){
        return(...args2) => {
            const fn = Symbol('fn');
            obj[fn] = this;
            obj[fn](...args1,...args2);
            delete obj[fn]
        }
    }

         

  • 相关阅读:
    Flex上传文件报“Error #2038”
    AMQ9558
    perl 运算符
    linux gdm 远程桌面访问
    perl 捕获变量
    android apk嵌套 从一个apk启动另外一个apk
    apk调用另一个apk
    ORA-01591 锁被未决分布式事务处理
    jQuery事件控制点击内容下拉
    作业还是作孽?——Leo鉴书79
  • 原文地址:https://www.cnblogs.com/jwenming/p/14499092.html
Copyright © 2011-2022 走看看