js中有关this指向的手写题 call、apply、bind

在JavaScript中,callapplybindFunction对象自带的三个方法,这三个方法的主要作用是改变函数中的this指向。

callapplybind方法的共同点和区别:
applycallbind 三者都是用来改变函数的this对象的指向的;
applycallbind 三者第一个参数都是this要指向的对象,也就是想指定的上下文(函数的每次调用都会拥有一个特殊值——本次调用的上下文(context)——这就是this关键字的值。);
applycallbind 三者都可以利用后续参数传参;
bind 是返回对应函数,便于稍后调用,bind也是一个‘’柯里化函数‘’;

applycall 则是立即调用 。

实现call函数 

Function.prototype.myCall = function (content) {
  content = content || window
  content.fn = this
  let args = Array.from(arguments).slice(1)
  let result = content.fn(...args)
  delete content.fn
  return result
}

function fun(args) {
  console.log("this.personSName ==>",this.personSName) //小明星
  console.log("this.age ==>",this.age) //20
  console.log("this.gender ==>",this.gender) //女
  console.log("args ==>",args) //'参数'

}

let obj = {
  personSName: '小明星',
  age: 20,
  gender: '女'
}

fun.myCall(obj,'参数')

打印结果


实现apply函数

Function.prototype.myApply = function (content) {
  content = content || window;
  content.fn = this;
  //arguments 函数所传的参数数组 (伪数组)
  //Array.from 将伪数组转成真正的数组  也可使用ES6的语法  [...arguments]
  let args = Array.from(arguments)
  let result;
  if (args[1] instanceof Array && args[1].length > 0) {
    result = content.fn(...args[1])
  } else {
    result = content.fn()
  }
  delete content.fn;
  return result;
}

function fun(args) {
  // console.log("this.name ==>",this.name)
  console.log("this.personSName ==>",this.personSName)
  console.log("this.age ==>",this.age)
  console.log("this.gender ==>",this.gender)
  console.log("args ==>",args)
  console.log("arguments ==>",[...arguments])
}

let obj = {
  personSName: '小明星',
  age: 20,
  gender: '女'
}

fun.myApply(obj,['123',456])

 打印结果

 实现bind函数

Function.prototype.myBind = function (content){
  content = content || window
  let args = [...arguments].slice(1);
  let _this = this
  return function F () {
    return _this.call(content,...args,...arguments)
  }
}

function fun() {
  // console.log("this.name ==>",this.name)
  console.log("this.personSName ==>",this.personSName)
  console.log("this.age ==>",this.age)
  console.log("this.gender ==>",this.gender)
  console.log("arguments ==>",...arguments)
}

let obj = {
  personSName: '小明星',
  age: 20,
  gender: '女'
}

let funcBind = fun.myBind(obj,'muBind的参数')//返回的是一个函数,需要调用函数才会执行

funcBind() //调用方法时也可传参数

打印结果

 文章到此结束,请大家多多指教

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值