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

JavaScript call() Method เรียกใช้ Method กับ Object อื่น

Function.prototype.call(thisArg, arg1, arg2...) เรียก Function โดยระบุ this เอง ส่ง Argument แบบแยกตัว

ตัวอย่าง

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>call() Method</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .sample { font-size: 18px; font-weight: 500; }
  </style>
</head>
<body>
  <h1>JavaScript call() Method</h1>
  <div class="sample"></div>
  <button class="Btn">CLICK HERE</button>
  <h3> Click to check adult with call() </h3>
  <script>
    let sampleEle = document.querySelector(".sample");
    let obj1 = { name: "Rohan", age: 22 };
    function checkAdult(vehicle, country) {
      if (this.age > 18) {
        sampleEle.innerHTML = this.name + " you are adult, can drive " + vehicle + " in " + country;
      } else {
        sampleEle.innerHTML = this.name + " not adult, cannot drive " + vehicle + " in " + country;
      }
    }
    document.querySelector(".Btn").addEventListener("click", () => {
      checkAdult.call(obj1, 'car', 'India');
    });
  </script>
</body>
</html>

คำอธิบาย

  • checkAdult.call(obj1, 'car', 'India'): this = obj1, vehicle='car', country='India'
  • call vs apply vs bind:
  • call(this, a, b, c) - ส่ง Argument แยกตัว
  • apply(this, [a, b, c]) - ส่ง Argument เป็น Array
  • bind(this, a, b) - คืน Function ใหม่ ผูก this + Arguments บางส่วน (Currying)

ผลลัพธ์

Rohan you are adult, can drive car in India