看板 Soft_Job 關於我們 聯絡資訊
※ 引述《peanut97 (丁丁)》之銘言: : 小弟在看Facebook教學頁面學習React.js : 常常看到bind寫法。 : http://imgur.com/53W47na : ref: : https://facebook.github.io/react/docs/thinking-in-react.html : google了一下,依然有看沒有懂。 : 請問有簡單解釋bind的教學頁面嗎? 理論上這應該到 ajax 版問啦... var mybaseFunction = function(str1,str2){ this.log(str1,str2); } var consoleHelloFunction = mybaseFunction.bind(console,"Hello"); /* 上面這行等價於 consoleHelloFunction = function(str){ return mybaseFunction.apply(console,["Hello",str]); } */ consoleHelloFunction("world"); -- 他可以改變 this,也能做 curry 效果。 -- I have a dream, it's silly but beautiful. -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 223.137.146.1 ※ 文章網址: https://www.ptt.cc/bbs/Soft_Job/M.1473324372.A.49B.html
Luos: console 是什麼? 09/08 17:28
console.log 可以看成是 printf
hcmlinj: 請教如果mybaseFunction是用arrow function如何bind呢? 09/08 17:41
hcmlinj: var mybaseFunction=(str1,str2) => this.log(str1,str2) 09/08 17:44
已經用 arrow function 的話就沒得改 this 啦,頂多只能 curry 了。 這就是為什麼 this 本來的設計比 bind 靈活得多。
DDR678: http://goo.gl/hy8eY8 09/08 17:57
clonn: console ~= c 的 printf 09/08 19:11
clonn: mybaseFuction.bind ... 用法同內文 09/08 19:12
mister12: 請問bind的優點是什麼呢? 09/08 19:37
CaptainH: 作用就是彌補js可笑的this設計 09/08 20:02
我不覺得可笑欸,原本的 this 雖然有複雜度, 但給了 mix-in 很多可以做的空間。 ※ 編輯: TonyQ (223.137.146.1), 09/08/2016 21:27:28 ※ 編輯: TonyQ (223.137.146.1), 09/08/2016 21:28:05
CaptainH: this 完全可以放到參數列表裡 09/08 22:06
CaptainH: 一舉消去了複雜性,更免去了bind call apply 等等冗餘 09/08 22:09
CaptainH: 函數 09/08 22:09
照 functional 的作法是這樣, 但如果有複雜的 state 要傳遞,那就會有額外的複雜度。 不用 this 的話, 那已經可說完全不是 bind or this 的問題了。XD
CRPKT: 沒有 this 物件模形怎麼做呢 09/08 22:26
y3k: Java跟JavaScript真的是狗跟熱狗啊.... 09/08 23:41
CoNsTaR: 不過會有 this 的問題是不是因為把該是 member 的做成了 09/08 23:52
CoNsTaR: free function 呢? 09/08 23:52
CoNsTaR: 完全不懂 javascript 還請指教 09/08 23:52
我會覺得你的描述反了喔。XD 如果把函示跟類別視為是一種契約論(約定 input/output/member ), this 實質上是一種額外的契約。 只是說在 js 裡面 member 的 function 比較靈活, 還可以單獨拆出來用而已。 我是覺得這塊比較接近 mix-in 的概念啦。 這塊牽扯到我們認為「function」該怎麼跟多個類別耦合... 是要走繼承呢,還是走契約(this)呢。 這其實是程式語言層次的問題。
TSW: 樓上不要在這邊問啦,去 ajax 版問 09/09 04:34
※ 編輯: TonyQ (223.137.146.1), 09/09/2016 05:51:32
Luos: 多謝這篇解決我多年的疑惑 09/09 14:53