JS原理——手写call、apply、bind方法

1. this指向

1.1 全局环境

        全局执行环境中,指向全局对象;

1.2 函数内部

        1)直接调用:

            ①指向全局对象(非严格模式下)

            ②指向undefined(严格模式下)

        2)对象方法调用

 2. 改变this指向

 2.1调用时指定

        1)call 调用;2)apply 调用。

2.2 创建时指定

        1)bind方法;2)箭头函数。

3. 手写call、apply、bind方法

3.1手写call方法:

Function.prototype.myCall = function(thisArg,...args) {
    const key = Symbol('key') //生成唯一key,避免函数名称与thisArg中的函数重复
    thisArg[key] = this  //由于func调用的myCall,所以this指向func
    const res = thisArg[key](...args) 
    delete thisArg[key]
    return res
}

const person = {
    name:'huihui'
}

const func = function(a,b) {
    console.log(this) //person
    console.log(a,b)  //1,2
    return a+b
}

const res = func.myCall(person,1,2)
console.log(res) //3

3.2手写apply方法

Function.prototype.myApply = function(thisArg,args) {
    const key = Symbol('key') //生成唯一key,避免函数名称与thisArg中的函数重复
    thisArg[key] = this  //由于func调用的myApply,所以this指向func
    const res = thisArg[key](...args) 
    delete thisArg[key]
    return res
}

const person = {
    name:'灰灰'
}

const func = function(a,b) {
    console.log(this) //person
    console.log(a,b)  //1,2
    return a+b
}

const res = func.myApply(person,[1,2])
console.log(res) //3

 3.3手写bind方法

Function.prototype.myBind = function(thisArg,...args) {
    return (...resArgs) => this.call(thisArg,...args,...resArgs)
}

const person = {
    name:'xiao灰'
}

const func = function(a,b) {
    console.log(this) //person
    console.log(a,b)  //1,2
    return a+b
}

const func1 = func.myBind(person,1)
const res = func1(2) 
console.log(res)//3

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值