DEV Community

Teerasak Vichadee
Teerasak Vichadee

Posted on • Updated on

บันทึกการใช้งาน call, apply, bind มันแตกต่างกันยังงัยนะ

สมมุติว่าเรามี

const action = () => {}
Enter fullscreen mode Exit fullscreen mode

เราจะใช้งานมันได้ 4 วิธี

1. ง่ายที่สุดเรียกมันตรงๆ

action()
Enter fullscreen mode Exit fullscreen mode

2. ใช้ call()

action.call(obj, a, b, c)
Enter fullscreen mode Exit fullscreen mode

call จะพิเศษกว่าการเรียกธรรมดา ตรงที่เราสามารถเอาค่าใน obj ไปใช้ใน action ได้ผ่าน "this"
เช่น

const obj = { name: 'ilumin' } 
const action = (a, b) => console.log(`Hello, ${this.name}, this is ${a} and ${b}.`)
action.call(obj, 'Anakin', 'Obiwan') // log: Hello, ilumin, this is Anakin and Obiwan.
Enter fullscreen mode Exit fullscreen mode

3. ใช้ apply

action.apply(obj, args)
Enter fullscreen mode Exit fullscreen mode

จริงๆแล้ว apply ก็เหมือน call เลย แต่พิเศษกว่าตรงที่มันรองรับการใส่ args เป็น array แต่ call ต้องเอาให้ชัวร์ว่ามีกี่ args เช่น

const obj = { name: 'ilumin' } 
const action = (a, b) => console.log(`Hello, ${this.name}, this is ${a} and ${b}.`)
action.apply(obj, ['Anakin', 'Obiwan']) // log: Hello, ilumin, this is Anakin and Obiwan.
Enter fullscreen mode Exit fullscreen mode

4. ใช้ bind

bind ถือว่าเป็นท่าที่เทพสุด เพราะเป็นการสร้าง function เอาไว้ใช้งานทีหลัง เช่น

const obj = { name: 'ilumin' } 
const action = (a, b) => console.log(`Hello, ${this.name}, this is ${a} and ${b}.`)
const bindedAction = action.bind(obj)
bindedAction('Anakin', 'Obiwan') // log: Hello, ilumin, this is Anakin and Obiwan.
Enter fullscreen mode Exit fullscreen mode

ไม่มีกฏตายตัวว่าอะไรดีที่สุด ทั้งหมดขึ้นอยู่กับบริบทของโค้ด เลือกเอาไปใช้อย่างมีสติ และตั้งมั่นอยู่บนความง่าย สะดวก สะอาด และประหยัด :D

Latest comments (2)

Collapse
 
ottoshi profile image
ottoshi

เหมือนข้อ 3 จะต้องเปลี่ยนจาก Call เป็น apply ไหมครับ

Collapse
 
ilumin profile image
Teerasak Vichadee

ใช่ครับ copy เพลิน :D ขอบคุณมากครับ