打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
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]
    }
}

     

 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
前端面试题整理——手写bind函数
详解 JavaScript 中的 this
从Ecma规范深入理解js中的this
JavaScript中的call、apply、bind
ES5 05 Function扩展
bind,call,apply模拟实现
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服