apply,call,bind手写

手写apply、call、bind
确定this 的值
  1. 全局执行环境

     <script>
        'use strict'
        console.log('222',this);
    </script>
    

    严格模式下和非严格模式下都是全局对象 (window)

  2. 函数内部

    'use strict'
    function  inFn() {
        console.log('inFn',this); 
    }
    

    严格模式下是undefined;非严格模式下是全局对象 (window)

  3. 对象方法

    'use strict'
    const peason = {
        name: '小毅',
        getName:()=>{
            console.log('getName', this); // window
            return this.name
        },
        setName(name) {
            console.log('setName', this); // 对用对象peason
            this.name = name
        }
    }
    

    严格模式下和非严格模式下结果一样;getName 方法是箭头函数,this是window; setName 方法是普通函数,this 是调用者 peason

手写call 方法
  1. 在Function 对象上实列上增加myCall 方法

    // 定义 myCall方法
    Function.prototype.myCall = function () {}
    // Object.prototype.myCall = function () {}
    
    // 
    function add(a, b) {}
    
    // 调用
    add.myCll({},a,b)
    

    1、Function或者Object 对象上定义myCall方法,调用的时候,可以根据原型链拿到myCall 方法

    2、add 方法也可以说是对象, 因为add instanceof Object ==> true

    3、根据上文《确定this 的值》 第三点,在对象方法里面的this是调用者,所以add.myCall({},a,b) , add 调用myCall ,此时myCall 方法里面的this 为 调用者:add 方法(对象)

    // 手写call
    Object.prototype.myCall = function (target, ...rest) {
        // this为调用者add,把add 方法放在target对象里
        target.fn = this
    	//再调用target下的fn,此时调用者是target,所以this为target
        const result = target.fn(...rest) 
        delete target.fn 
        return result
    }
    
    const peason = {name: '小毅'}
    // 调用
    add.myCall(peason,1,2)
    
  2. 优化,上面一个版本的call ,可能会把target 对象的fn 属性覆盖掉,使用

    Object.prototype.myCall = function (target, ...rest) {
       const key = new Symbol()
        target = target || {}
        target[key] = this
        const result = target.fn(...rest)
        delete target[key]
        return result
    }
    
手写apply 方法

与call 类似,只是apply 接收的参数是数组

Function.prototype.myApply = function (target,rest) {
   const key = new Symbol()
    target = target || {}
    target[key] = this
    const result = target.fn(rest)
    delete target[key]
    return result
}
手写bind

bind 函数绑定是,没有执行,所以返回的是一个函数;

myBind 方法内的this 是调用者add 方法

myBind 内return 的是箭头函数,所以this 也是add方法

this.mycall 相当于 add.mycall ,同上文 mycall原理相当

// mybind 方法
Function.prototype.myBind=function (target,...rest){
    return (...rest2)=>{
        this.myCall(target,...rest,rest2)
    }
}

// 累加  
add(num1,num2,num3,num4){}

// add 调用bind
add.myBind(peason,1,2)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值