手写 bind
一:先实现 apply 参数(ctx,args)
- 上下文 ctx 不存在默认 window
- 声明 ctx.fn 变量,并将 this(即 fn.myApply()中的调用者 fn)赋予 ctx.fn
- fn 函数 拷贝到 ctx.fn,这样函数的 this 指向自动变成 ctx
- 调用新函数的到返回值 result
- 删除无用 ctx.fn 属性
- 返回 result
二:再实现 bind 参数(fn,obj)
- 返回函数 return function (...args)
- 继续返回 apply 绑定 this 的函数
return function(...args){
return fn.apply(obj,args)
}
Function.prototype.myApply = function (ctx,args) {
// 模仿浏览器(ctx 等于 fn.myCall(obj) 中的 obj)
ctx = ctx || window
// 将函数设为对象的属性 ctx.fn = fn (this等于fn.myCall(obj) 中的 fn)
ctx.fn = this
// 执行该函数 ctx.fn(参数)
let result = ctx.fn(...args)
// 删除该函数 delete ctx.fn
delete ctx.fn
return result
}
Function.prototype.myBind = function (fn, obj) {
return function(...args) { // 返回bind绑定
// return fn.myApply(obj,rest) // 返回执行调用
return fn.apply(obj,args) // 返回执行调用
}
}
使用方法:
let obj = {
value: 1
}
function foo(a, b) {
console.log(this.value)
return a + b
}
// 就是把 foo 函数里的 this 指向,指向 obj
foo.myBind(foo, obj)(2, 3)