js apply、call、bind

apply、call、bind

区别

执行时机参数传参改变this指向
apply直接执行第二个参数是数组或类数组可以
call直接执行一个一个传可以
bind调用的时候一个一个传可以

使用bind\call\apply

let obj1 = {
	grade: 'B',
	sayName: function(name = 'obj1', age = '10000') {
			console.log(`我是${name},今年${age}岁, 成绩:${this.grade}`)
	}
}
let obj2 = {
	grade: 'A',
}
obj1.sayName()
obj1.sayName.apply(obj2, ['obj2', '18'])
obj1.sayName.call(obj2, 'obj2', '18')
obj1.sayName.bind(obj2, 'obj2', '18')()

动手实现

Function.prototype.apply = function(context){
	context = context || window
	let args = arguments[1] || []
	context.fn = this
	let res = context.fn(...args)
	delete context.fn //删除context多余fn
	return res
}
obj1.sayName.apply1(obj2, ['obj2', '18']) //我是obj2,今年18岁, 成绩:A

//call 和 bind是包装在apply上的语法糖
Function.prototype.call1 = function (context) {
	let argu = []
	for(let i = 1; i < arguments.length; i++) {
		argu.push(arguments[i])
	}
	this.apply1(context, argu)
}
obj1.sayName.call1(obj2, 'obj2', '18')//我是obj2,今年18岁, 成绩:A

Function.prototype.bind1 = function (context) {
	let self = this
	let arr = Array.prototype.slice.call(arguments, 1);
	return function() {
		let new_arr = Array.prototype.slice.call(arguments);
		return self.apply(context, arr.concat(new_arr))
	}
}
obj1.sayName.bind1(obj2, 'obj2', '18')(1,2)//我是obj2,今年18岁, 成绩:A

参考链接:

5分钟带你搞懂 Javascript 中的this(包含apply、call、bind) - 掘金 (juejin.cn)

JS手写call apply bind (详细)(面试)-CSDN博客

  • 13
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值