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

วิธีเรียกใช้ JavaScript Function เป็น Method

ฟังก์ชันใน JavaScript สามารถกำหนดให้เป็น Property ของ Object (Method) และเรียกใช้ด้วยวงเล็บ ()

ตัวอย่าง

<html>
  <head>
    <script>
      var employee = { 'empname': 'David' };

      employee.name = function() {
        return this.empname;
      };

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

ผลลัพธ์

David

รายละเอียด

  1. var employee = { 'empname': 'David' } - สร้าง Object มี Property empname
  2. employee.name = function() { ... } - กำหนด Function ให้ Property name (กลายเป็น Method)
  3. this.empname - ใน Method this ชี้ไปที่ Object ที่เรียก (employee)
  4. employee.name() - เรียก Method ผ่าน Object

Method Shorthand (ES6)

const employee = {
  empname: 'David',
  // แทน name: function() {}
  name() {
    return this.empname;
  }
};

การสร้าง Method แบบ Dynamic

const obj = {};

function addMethod(obj, name, fn) {
  obj[name] = fn;
}

addMethod(obj, 'greet', function() {
  return 'Hello ' + this.name;
});

obj.name = 'World';
obj.greet(); // "Hello World"

Binding this (สำคัญ)

const obj = {
  value: 42,
  getValue: function() { return this.value; }
};

const fn = obj.getValue;
fn(); // undefined (this หายไป)

const boundFn = obj.getValue.bind(obj);
boundFn(); // 42 (this ผูกไว้)

สรุป: Function กลายเป็น Method เมื่อเป็น Property ของ Object เรียกด้วย obj.method() แล้ว this จะชี้ไปที่ obj