JavaScript Function bind()

การยืมฟังก์ชัน (Function Borrowing)

ด้วยการใช้วิธี bind() ตัวแปรหนึ่งสามารถยืมวิธีจากตัวแปรอื่น

ตัวอย่างด้านล่างนี้สร้าง 2 ตัวแปร (person และ member)

ตัวแปร member ยืมวิธี fullname ของตัวแปร person

ตัวอย่าง

const person = {
  firstName:\"Bill\",
  lastName: "Gates",
  fullName: function () {
    return this.firstName + \" \" + this.lastName;
  }
}
const member = {
  firstName:\"Hege\",
  lastName: "Nilsen",
}
let fullName = person.fullName.bind(member);

Try it yourself

รักษา this

บางครั้งจำเป็นต้องใช้วิธี bind() เพื่อป้องกันการสูญเสีย this.

ในตัวอย่างด้านล่างนี้ ตัวแปร person มีวิธี displaythis หมายถึงตัวแปร person:

ตัวอย่าง

const person = {
  firstName:\"Bill\",
  lastName: "Gates",
  display: function () {
    let x = document.getElementById("demo");
    x.innerHTML = this.firstName + " " + this.lastName;
  }
}
person.display();

Try it yourself

เมื่อฟังก์ชันใช้เป็นคำสั่งกลับthis จะสูญเสียไป

ตัวอย่างนี้จะพยายามแสดงชื่อใน 3 วินาทีต่อไป แต่มันจะแสดง undefined:

ตัวอย่าง

const person = {
  firstName:\"Bill\",
  lastName: "Gates",
  display: function () {
    let x = document.getElementById("demo");
    x.innerHTML = this.firstName + " " + this.lastName;
  }
}
setTimeout(person.display, 3000);

Try it yourself

วิธี bind() แก้ปัญหานี้

ในตัวอย่างด้านล่างนี้ วิธี bind() ใช้เพื่อจับคำสั่ง person.display กับ person

ตัวอย่างนี้จะแสดงชื่อใน 3 วินาทีต่อไป

ตัวอย่าง

const person = {
  firstName:\"Bill\",
  lastName: "Gates",
  display: function () {
    let x = document.getElementById("demo");
    x.innerHTML = this.firstName + " " + this.lastName;
  }
}
let display = person.display.bind(person);
setTimeout(display, 3000);

Try it yourself

What is this?

In JavaScript,this keyword refersobject.

refersWhichobject depends on the way it is called (used or called).

According to its usage, the keyword this refers to different objects:

  • In the object method,this refers to thisobject.
  • used alone,this refersglobal object.
  • In the function,this refersglobal object.
  • In the function, in strict mode,this is undefined.
  • In the event,this refer to the elements that receive eventselements.
  • call(), apply(), and bind() methods can be used to this refers toAny object.

Note:this is not a variable. It is a keyword. You cannot modify this Value.

See also:

Tutorial:JavaScript this