手写apply call bind

Function.prototype._apply = function (context, args) {
context = context || window
context.fn = this
args = args ? args : []
console.log(context)
let res = context.fn(…args)
delete context.fn
return res
}
let applyObj = {
name: ‘校园’
}
let applyFun = function (a, b) {
console.log(a, b, this.name)
}
applyFun._apply(applyObj, [1, 2])

Function.prototype._call = function (obj, …args) {
obj = obj || window
obj.fn = this
args = args ? args : []
let res = obj.fn(…args)
delete obj.fn
return res
}
let callObj = {
name: ‘小袁’
}
let callFun = function (a, b, c) {
console.log(a, b, c, this.name)
}
callFun.call(callObj, 1, 2, 3)

Function.prototype._bind = function (context, …args) {
context = context || window
let fn = this
return function newFun(…newArgs) {
let res
if (this instanceof newFun) {
res = new fn(…args, …newArgs)
} else {
res = fn._call(context, …args, …newArgs)
}
console.log(‘res’, res)
return res
}
}
let bindObj = {
name: ‘bind小袁’
}
let bindFnc = function (a, b, c, d) {
console.log(a, b, c, d, this.name)
}
let b = bindFnc._bind(bindObj, 1, 2, 3)
b(‘444’)
let a = new b(‘aaaa’)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值