温故而知新:柯里化 与 bind() 的认知
生活随笔
收集整理的這篇文章主要介紹了
温故而知新:柯里化 与 bind() 的认知
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
?
什么是柯里化?
科里化是把一個多參數(shù)函數(shù)轉(zhuǎn)化為一個嵌套的一元函數(shù)的過程。(簡單的說就是將函數(shù)的參數(shù),變?yōu)槎啻稳雲(yún)?#xff09;
?
關(guān)于bind的認知
bind 和 call / apply 很相似,都可以改變 this 的指向,也都可以傳遞參數(shù)。但還是有一些區(qū)別:
?1)bind不會立即執(zhí)行函數(shù),而是返回一個新函數(shù)。譬如在 React 中我們經(jīng)常用 bind 將函數(shù)的 this 指向組件本身:
export default class ClickOutside extends Component {constructor(props) {super(props)this.getContainer = this.getContainer.bind(this)}getContainer(ref) {this.container = ref} }?
2)除了 this 以外的參數(shù),會把原函數(shù)的參數(shù)位給占領(lǐng)(擾亂王?鳩占鵲巢?小三上位?),也就是預(yù)設(shè)值綁定(賦值):
// demo1: 演示預(yù)設(shè)綁定 x 和 y 的參數(shù) const add = (x, y, z) => x + y + z; add.bind(null, 1, 2)(3) // => 6 , 等價于 add(1, 2, 3)// demo2: 演示多次bind const add = (x, y) => x + y; const myadd = add.bind(null, 1).bind(null, 2) myadd() // => 3 , 等價于 add(1, 2)// demo3: 和...args這種數(shù)組解構(gòu)結(jié)合使用時可別懵了 O(∩_∩)O哈哈~ const add = (...args) => console.log(args, args.length); const myadd = add.bind(null, 1).bind(null, 2).bind(null, 3).bind(null, 4).bind(null, 5) myadd() // => [1, 2, 3, 4, 5] 5這種特性實際上和 偏應(yīng)用 很相似,區(qū)別僅僅在于偏應(yīng)用不需要關(guān)注 this 的綁定。
偏應(yīng)用的目的只有一個,那就是通過預(yù)設(shè)值減少函數(shù)的參數(shù)位,達到簡化函數(shù)、惰性函數(shù)、可重用函數(shù)等目的。
總結(jié)
以上是生活随笔為你收集整理的温故而知新:柯里化 与 bind() 的认知的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 女人梦到自己骑摩托车是什么意思
- 下一篇: 跨库数据表的运算