面试-this-手写call, apply -bind

this 的指向 参考学习

//this-引用函数的执行环境对象

const handle={
  test:'this在哪里',
  func:function t() {
    console.log(this.test);
  }
}

handle.func()//有值
let a=handle.func
a()//undefined

//call的原理, 改变函数this指向, 是的调用函数可以使用方法
//拿到指针??
//需要重新思考this 的含义
//this 指向函数调用的最近的对象

// 普通函数,由于闭包函数是window执行的,所以this指向window;
// 箭头函数的this指向函数创建时的作用域。

Object.prototype.myCall=function(context,...args){
  if(!context||context==null){
    context=window
  }else{
    context=Object(context)//考虑基本类型
  }
  let fn=Symbol()
  context[fn]=this
  let res=context[fn](...args)
  delete context[fn]
  return res
}

Object.prototype.myApply=function(context,...args){
  if(!context||context==null){
    context=window
  }else{
    context=Object(context)//考虑基本类型
  }
  let fn=Symbol()
  context[fn]=this
  let res=context[fn](args)
  delete context[fn]
  return res
}

Object.prototype.myBind=function(context,...args){
  const fn=this
  return function(...args1){
    fn.call(context,...args,...args1)
  }
}
Object.prototype.myBind1=function(fn,args){
  return function(){
    fn.apply(args,arguments)
  }
}

function TestBind(name,age) {
  console.log(name,age);
}
function b(){};
let c=TestBind.myBind(b,'小明','20')
c(11)


//微任务 ->dom渲染 ->宏任务
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值