bind polyfill

bind use

func.bind(thisArg[, arg1[, arg2[, …]]])
thisArg改变目标函数this指向的值,若为基本类型将转化为基本类型对应的包装对象

当函数直接调用

// bind使用
function func(...arg){
    console.log(this)
    console.log(arg)
}

func.prototype.fn = function(){
    console.log('fn')
}

let newFunc = func.bind([1,2,3],1,2,3,4,5)

// let newFunc = func.bind(1,1,2,3,4,5)

newFunc()

当构造函数使用

let f = new newFunc() 

console.log(f)

模拟写一个bind方法

// ES5版本
Function.prototype.customBindES5 = function(context){
    // 目标函数
    let _this = this
    let arg = Array.prototype.slice.call(arguments,1) // 转数组
    // let arg = Array.from(arguments)
    // let arg = [ ...arguments ]

    // 返回新函数
    return function(){
        let newArg = Array.prototype.slice.call(arguments, 0)
        // let newArg = Array.from(arguments)
        // let newArg = [ ...arguments ]
        return _this.apply(context, arg.concat(newArg))
    }
}


// 初始版本 v1
Function.prototype.customBind = function(context, ...rest){
    // 目标函数
    let _this = this
    let arg = rest
    // 返回新函数
    return function(...rest){
        let newArg = rest
        return _this.apply(context, [ ...arg, ...newArg ])
    }
}


/*
    目标函数:调用bind的函数,func.bind func就称之为是目标函数
    新函数:bind返回的函数,let newFunc = func.bind() newFunc就称之为新函数
*/

/*
    1. 返回的函数作为构造函数,新函数要继承目标函数的原型
    2. 一旦把新函数当成构造函数了,目标函数的this应该指向实例对象
*/
// 考虑到原型链 v2
Function.prototype.customBind = function(context, ...rest){
    // // 目标函数
    let _this = this
    let arg = rest

    let Bound = function(...rest){
        let newArg = rest
        // 如果这个函数作为了构造函数,那么目标函数的this,应该执行的是实例对象
        // 如果这个不是作为构造函数,目标函数中的this还指向context
        // console.log(this,this instanceof Bound,11)
        let thisArgSelf = this instanceof Bound ? this : context
        _this.apply(thisArgSelf, [ ...arg, ...newArg ])
    }

    // Object.create 用来创建以某一个对象作为原型的对象的
    Bound.prototype = Object.create( this.prototype )
    Bound.prototype.constructor = this

    // 返回新函数
    return Bound
}


function fn(...arg){
    console.log(this)
    console.log(arg)
}

fn.prototype.run = function(){}

let newFn = fn.customBind({a:1}, 1, 2, 3)
newFn(4,5,6)
// new newFn(4,5,6)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值