手写call,apply,bind

1. call

Function.prototype.myCall = function (context) {
	// context 接收第一个参数 如果没有默认用window
	context = context || window
	// 给context.fn 或其他属性赋值为函数, 即myCall的调用者改变函数的this 指向context
	context.fn = this
	// 获取传入的参数
	const args = [...arguments].slice(1)
	// 通过...展开并传给fn args 获取执行结果 result 并返回
	const result = context.fn(...args)
	// 删除fn
	delete context.fn
	return result
}

2. apply

Function.prototype.myApply = function (context) {
	context = context || window
	context.fn = this
	let result
	if (arguments[1]) {
		result = context.fn(...arguments[1])
	} else {
		result = context.fn()
	}
	delete context.fn
	return result
}

3. bind

Function.prototype.myBind = function (context) {
	context = context || window
	const args = [...arguments].slice(1)
	let _this = this
	return function f () {
		return _this.apply(context, [...args, ...arguments])
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值