DEV Community

Lumin
Lumin

Posted on • Edited on

5 2

บันทึกการใช้งาน 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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (2)

Collapse
 
ottoshi profile image
ottoshi

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

Collapse
 
ilumin profile image
Lumin

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

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay