手写 call、apply、bind方法

call


// call() 方法使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数。
// 修改this指向, 相当于给ctx新增一个函数(this指向的函数), 函数可以引用ctx的属性
Function.prototype._call = function (ctx = window, ...args) {
    ctx.fn = this
    const result = ctx.fn(...args)
    delete ctx.fn
    return result
}
const obj = {
    name: '11',
    fun() {
        console.log(this.name);
    }
}
const obj2 = { name: '22' }
obj.fun() // 11
obj.fun.call(obj2) // 22
obj.fun._call(obj2) // 22

apply


// apply() 方法使用一个指定的 this 值和单独给出的一个或多个数组参数来调用一个函数。
Function.prototype._apply = function (ctx, args) {
    ctx.fn = this
    const result = ctx.fn(...args)
    delete ctx.fn
    return result
}
const obj = {
    name: '11',
    fun() {
        console.log(this.name);
    }
}
const obj2 = {name: '22'}
obj.fun() // 11
obj.fun.apply(obj2) // 22
obj.fun._apply(obj2) // 22

bind


// bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。
Function.prototype._bind = function (ctx, ...args) {
    const _self = this
    const bindFn = (...reset) => {
        return _self.call(ctx, ...args, ...reset)
    }
    return bindFn
}
const obj = {
    name: '11',
    fun() {
        console.log(this.name);
    }
}
const obj2 = {name: '22'}
obj.fun()
const fn = obj.fun.bind(obj2)
const fn2 = obj.fun._bind(obj2)
fn() // 22
fn2() // 22
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值