call apply bind 的区别
- call(obj)/apply(obj):调用函数,指定函数中this为第一个参数的值
- bind(obj):返回一个新的函数,新函数内部会调用原来的函数,this为bind指定的第一个参数
- 如果obj是null/undefined,this为window
function fn(a, b) {
this.xxx = 3
console.log(a, b, this)
}
fn(1, 2)
console.log(xxx)
const obj = {
m: 0
}
fn.call(obj, 1, 2)
fn.apply(obj, [1, 2])
fn.call(undefined, 1, 2)
fn.call(null, 1, 2)
fn.bind(obj,1,2)(4,5)
应用
- 把维数组转换为真正的数组
手写call apply bind
- 手写 call
Function.prototype.call = function (obj, ...args) {
console.log('call')
if (obj === null || obj === undefined) {
obj = window
}
obj.temFn = this
const result = obj.temFn(...args)
delete obj.temFn
return result
}
- 手写apply 和apply几乎一样
Function.prototype.apply = function (obj, args) {
console.log('apply')
if (obj === null || obj === undefined) {
obj = window
}
obj.temFn = this
const result = obj.temFn(...args)
delete obj.temFn
return result
}
- 手写bind
Function.prototype.bind = function (obj, ...args) {
console.log('bind')
return (...args2) => {
return this.call(obj, ...args, ...args2)
}
}