Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

Function vs Method — ความแตกต่างคืออะไร?

ง่ายที่จะสับสนกับ thuật ngữ JavaScript โดยเฉพาะเมื่อบางนิยาม聽起來คล้ายกัน Function และ Method ไม่ใช่ข้อยกเว้น

ก่อนอื่น ให้จดจำ 2 ข้อเท็จจริง:

  • Method คือ Function
  • Function คือ Function (สิ่งที่คุณสามารถเรียกใช้เพื่อรัน/execute โค้ด)

ความแตกต่างระหว่าง Function และ Method อยู่ที่ วิธีการใช้งาน

Function ธรรมดา มีอยู่ด้วยตัวเอง และถูกเรียกใช้โดยการเรียก Function

function alertMessage() {
  alert("Alert message triggered!");
}
// เรียกใช้ alertMessage function
alertMessage();

Method เป็นประเภทหนึ่งของ Function ที่ ถูกกำหนดให้กับ property ของ object

อีกนัยหนึ่ง: Method คือ Function ที่เป็น property ของ Object

const blackFridayDeals = {
  sony: 'Playstation 5',
  discountPopup: function() {
    alert(`Get 50% off ${this.sony} only today!`);
  },
};

blackFridayDeals.discountPopup();

ในโค้ดด้านบน มี object ชื่อ blackFridayDeals หนึ่งใน property คือ discountPopup ซึ่งมี function ถูกกำหนดไว้ ทำให้ execute alert dialog (ซึ่งเป็น built-in JavaScript method)