柯里化
”函数柯里化”是指将多变量函数拆解为单变量的多个函数的依次调用,
add(1,2,3)
add(1)(2)(3)
其实就利用闭包,将变量都存起来并返回一个函数,最后在执行这个函数
柯里化的作用
-
参数复用
-
提前返回
-
延迟运行
(以上三种作用可以看这篇博客函数柯里化_runner_123的博客-CSDN博客_函数柯里化)
function curry() {
let allArgs = [...arguments]
// 返回一个新函数
function curried() {
allArgs.push(...arguments)
return curried
}
// 重写toString
curried.toString = function() {
return allArgs.reduce((prev, curr) => (prev + curr), 0)
}
return curried;
}
let add = curry(3);
/* let a = add(1)(2)(3)
console.log(a.toString()); */
/* let a = add(1, 2)(3, 4)(5, 6)
console.log(a.toString()); */
这里先写个初步版本的柯里化函数,后面还需改善,需要让toString自动化执行,不需要手动执行,今天折腾了一下午自动执行toString结果都输出函数主体,不知道怎么回事,后面有空再折腾吧(可能得继续理解一下这篇博客 https://juejin.cn/post/6864378349512065038#heading-27 )
myCall
// 不能用箭头函数,会绑定到window,箭头函数的this指向它创建时候的环境
Function.prototype.myCall = function(context, ...args) {
context = context || window
const key = Symbol()
context[key] = this
let res = context[key](...args)
delete context[key]
return res
}
function go(a, b) {
console.log(this.c + a + b);
}
let obj = {
c: 10
}
go.myCall(obj, 1, 4)
myApply
Function.prototype.myApply = function(context, args) {
context = context || window
let key = Symbol()
context[key] = this
let res = context[key](...args)
delete context[key]
return res
}
function go(a, b) {
console.log(this.c + a + b);
}
let obj = {
c: 20
}
go.myApply(obj, [10, 20])
myBind
Function.prototype.myBind = function(context, ...args) {
return (...restArgs) => this.call(context, ...args, ...restArgs)
}
function go(a, b) {
console.log(this.c + a + b);
}
let obj = {
c: 10
}
let r = go.myBind(obj, 100, 200)
r()