• 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]
        }
    }

         

  • 相关阅读:
    实现 AD 采样,使用 LCD1602 显示 AD 数值
    数据结构(C语言)—排序
    Keil uVision4 创建51单片机工程
    51单片机 方波
    51单片机串口中断实验
    51单片机 中断控制蜂鸣器
    串口通信
    定时器与计数器
    中断系统
    《web前端设计基础——HTML5、CSS3、JavaScript》 张树明版 简答题简单整理
  • 原文地址:https://www.cnblogs.com/jwenming/p/14499092.html
Copyright © 2020-2023  润新知