手写bind
方法1. 使用 apply
Function.prototype.myBind = function () {
const t = Array.prototype.shift.call(arguments)
const args = arguments
const self = this
return function () {
self.apply(t, args)
}
}
const obj = { x: 111 }
const fun = function (v) {
console.log(this, v)
}
fun.myBind(obj, 222)()
方法2. 不使用 apply
Function.prototype.myBind2 = function () {
const t = Array.prototype.shift.call(arguments)
const args = arguments
const self = this
return function () {
t.__proto__.temp = self
t.temp(...args)
}
}
const obj = { x: 111 }
const fun = function (v) {
console.log(this, v)
}
fun.myBind2(obj, 333)()
手写 call
Function.prototype.myCall = function () {
const t = Array.prototype.shift.call(arguments)
const args = arguments
const self = this
self.apply(t, args)
}
Function.prototype.myCall2 = function () {
const t = Array.prototype.shift.call(arguments)
const args = arguments
t.__proto__.temp = this
t.temp(...args)
}
const obj = { x: 111 }
const fun = function (v, k) {
console.log(this, v, k)
}
fun.myCall(obj, 222, 444)
fun.myCall2(obj, 333, 55)
手写apply
Function.prototype.myApply = function () {
const t = Array.prototype.shift.call(arguments)
const args = arguments
const self = this
self.call(t, ...args)
}
Function.prototype.myApply2 = function () {
const t = Array.prototype.shift.call(arguments)
const args = arguments
t.__proto__.temp = this
t.temp(...args)
}
const obj = { x: 111 }
const fun = function (args) {
console.log(this, args)
}
fun.myApply(obj, [222, 444])
fun.myApply2(obj, [333, 55])