Appearance
bind,apply,call 区别
都是用于改变函数执行时 this
的指向。
call() 和 apply() 的区别?
它们的作用一模一样,区别仅在于传入参数的形式的不同,apply
第二个参数为数组,call
第二个参数开始依次传入。
call
js
Function.prototype.myCall = function (context, ...rest) {
context.fn = this
const result = context.fn(...rest)
delete context.fn
return result
}
apply
js
Function.prototype.myApply = function (context, rest) {
context.fn = this
const result = context.fn(...rest)
delete context.fn
return result
}
bind
js
Function.prototype.myBind = function (context) {
const self = this
return function (...rest) {
return self.call(context, rest)
}
}
应用场景
- 利用
bind
快速完成柯里化;
js
function sum(a, b) {
return a + b
}
const temp = sum.bind(null, 5)
console.log(temp(5)) // 5
console.log(temp(10)) // 10