- 1、# 偏应用函数与柯里化
//返回一个函数:处理两个函数的所有参数
const partial = (f, ...args) =>
(...moreArgs) => f(...args, ...moreArgs)
//原函数定义:f
const add3 = (a, b, c) => a + b + c
const fivePlus = partial(add3, 2, 3) //返回一个函数f: (c) => 2 + 3 + c
fivePlus(4) // 9
柯里化是将一个多参数函数转换成多个单参数函数,也就是将一个 n 元函数转换成 n 个一元函数
const curry = function(fn){
return function curryFn(...args){
if(args.length<fn.length){
return function(...newArgs){
return curryFn(...args,...newArgs)
}
}else{
return fn(...args)
}
}
}
let add = (a,b,c)=>a+b+c
// 柯里化
add = curry(add)
console.log(add(1)(2)(3)) // 输出 6
- 2、闭包应用:立即执行函数 IIFE == Immediately-Invoked Function Expressions
- 1、创建临时独立作用域
- 2、解决变量名冲突
- 3、形参使用简洁变量名
- 4、解决var的循环陷阱
- 5、类似jQuery类库包装
- 6、webpack打包模块:入口是iife,模拟函数也都是iife
- 3、this的使用场景:
this的确定由执行上下文决定。- 函数直接执行时,
this指向global或者window,严格模式下指向undefined。 - 函数被当作对象方法调用时,
this指向调用它的对象。 - 函数被
call,apply,bind调用时,this为其绑定值。 - 函数被
new调用时,this指向new左侧变量。 - 箭头函数没有
this,其this是父级this。 - 一些方法会修改
this值,如vue,addEventListener
- 函数直接执行时,