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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (2)

Collapse
 
ottoshi profile image
ottoshi

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

Collapse
 
ilumin profile image
Lumin

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

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more