保留重複參數的函式,不必每次傳遞
// 一個簡單字串組合函式 function profile(pro, place, name) { return 'My name is ' + name + ', I am a ' + pro + ' from ' + place; } // 在 profile 上使用 bind 建立 Curry 函式, 也就是建立一個具有所需引數固定子集的代理函式 // 新增組合字串方法, 前面兩個參數是固定的, 因為沒有使用到 this, 所以不設定接收者 var dancer = profile.bind(null, 'dancer', 'Taipei'); dancer('Ian'); // "My name is Ian, I am a dancer from Taipei" dancer('Joe'); // "My name is Joe, I am a dancer from Taipei" var names = ['Peter', 'Terry', 'Alice']; var writers = names.map(profile.bind(null, 'writer', 'Tainan')); console.log(writers);
writers 顯示 :
["My name is Peter, I am a writer from Tainan", "My name is Terry, I am a writer from Tainan", "My name is Alice, I am a writer from Tainan"]
沒有留言:
張貼留言