第21天 bind、call、apply 区别

本文深入探讨JavaScript中改变函数上下文的call、apply和bind方法,阐述它们的用途和区别。通过实例讲解如何手动实现这三个方法,包括考虑this的指向、参数传递和柯里化。同时,介绍了bind的特殊性,即返回新函数并允许部分应用参数。
摘要由CSDN通过智能技术生成

call 和 apply 都是为了解决改变 this 的指向。作⽤都是相同的,只是传参的⽅式 不同。
除了第⼀个参数外, call可以接收⼀个参数列表, apply 只接受⼀个参数数组

let a = {
 value: 1 }
function getValue(name, age) {
 console.log(name)
 console.log(age)
 console.log(this.value) }
getValue.call(a, 'yck', '24')
getValue.apply(a, ['yck', '24'])

bind 和其他两个⽅法作⽤也是⼀致的,只是该⽅法会返回⼀个函数。并且我 们可以通过 bind 实现柯⾥化

1.如何实现⼀个 bind 函数

  • 不传⼊第⼀个参数,那么默认为 window
  • 改变了 this 指向,让新的对象可以执⾏该函数。那么思路是否可以变成给新的对象添加
    ⼀个函数,然后在执⾏完以后删除?
Function.prototype.myBind = function (context) {
 if (typeof this !== 'function') {
 	throw new TypeError('Error')
 }
 var _this = this
 var args = [...arguments].slice(1)
 // 返回⼀个函数
 return function F() {
 // 因为返回了⼀个函数,我们可以 new F(),所以需要判断
 if (this instanceof F) {
	 return new _this(...args, ...arguments)
 }
 	return _this.apply(context, args.concat(...arguments))
 }
}

2.如何实现⼀个 call 函数

Function.prototype.myCall = function (context) {
 var context = context || window
 // 给 context 添加⼀个属性
 // getValue.call(a, 'yck', '24') => a.fn = getValue
 context.fn = this
 // 将 context 后⾯的参数取出来
 var args = [...arguments].slice(1)
 // getValue.call(a, 'yck', '24') => a.fn('yck', '24')
 var result = context.fn(...args)
 // 删除 fn
 delete context.fn
 return result
}

3.如何实现⼀个 apply 函数

Function.prototype.myApply = function (context) {
 var context = context || window
 context.fn = this
 var result
 // 需要判断是否存储第⼆个参数
 // 如果存在,就将第⼆个参数展开
 if (arguments[1]) {
 	result = context.fn(...arguments[1])
 } else {
	 result = context.fn()
 }
 delete context.fn
 return result
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值