javaScript手写bind及思路

89 阅读1分钟

一行代码,一行注释解说

注意,bind方法是在手写call方法的基础上进行优化的


//老生常谈,bind方法是普通函数的方法,所以,写在函数的原型链上
//特点,不会立即执行,且返回的是函数,可分次传参
//手写call方法
Function.prototype.myCall = function(obj,...args){
    const obj = obj ? Object(obj) : window
    const fn = Symbol(obj)
    obj[fn] = this
    const res = obj[fn](...args)
    delete obj[fn]
    return res
}
Function.prototype.myBind = function(obj,rest1){
    //第一步,先赋值this
    const fn = this
    // 返回一个函数,且可以再次进行传参
    return function(...rest2){
        // 使用手写Call的方法进行优化的部分
        return fn.myCall(obj,...rest1.concat(rest2))
    }
}

-----------------------------------------------------------------------

// 使用方法

var obj = {
    name:'张三'
}
fn1(...rest){
    console.log(this.name,...rest)
}

fn1.bind(obj,15)(33,55)
fn1.myBind(obj,15)(33,55)