首页 > 移动平台 > 详细

call、apply、bind函数的理解以及手写。

时间:2021-03-08 14:01:39      阅读:49      评论:0      收藏:0      [点我收藏+]

理解

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

     

 

call、apply、bind函数的理解以及手写。

原文:https://www.cnblogs.com/jwenming/p/14499092.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!