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

ความแตกต่างระหว่าง Functions และ Methods ใน JavaScript

ใน JavaScript Functions และ Methods คือสิ่งเดียวกัน ทั้งคู่คือฟังก์ชัน แตกต่างกันแค่ บริบท (Context) ที่เรียกใช้

Function (ฟังก์ชัน)

ฟังก์ชันอิสระ ไม่ได้ผูกกับออบเจ็กต์

function functionName(param1, param2) {
  // code
}

functionName(); // เรียกโดยตรง

Method (เมธอด)

ฟังก์ชันที่เป็น Property ของออบเจ็กต์ เรียกผ่านออบเจ็กต์นั้น

<html>
  <head>
    <script>
      var employee = {
        empname: "David",
        department: "Finance",
        id: 002,
        details: function() {
          return this.empname + " with Department " + this.department;
        }
      };

      document.write(employee.details());
    </script>
  </head>
  </html>

ผลลัพธ์

David with Department Finance

ความแตกต่างสำคัญ: this Binding

บริบทthis ชี้ไปที่
Function เรียกโดยตรง func()Global (window) หรือ undefined (strict mode)
Method เรียกผ่านออบเจ็กต์ obj.method()ออบเจ็กต์นั้น (obj)
Constructor new Func()Instance ใหม่ที่สร้างขึ้น
call/apply/bindตามที่ระบุ
Arrow FunctionLexical scope (this จากบริบทรอบนอก)

ตัวอย่าง this Binding

var obj = {
  value: 42,
  method: function() { return this.value; },
  arrow: () => this.value // this = window (lexical from global)
};

obj.method(); // 42
obj.arrow();  // undefined (หรือ global value)

var fn = obj.method;
fn(); // undefined (this หายไป)

สรุป: Method คือ Function ที่เป็น Property ของ Object ความแตกต่างหลักคือ this binding