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

ตัวดำเนินการ new ใน JavaScript

ตัวดำเนินการ new ใช้สำหรับสร้าง Instance (อินสแตนซ์) จาก Constructor Function หรือ Class ทำงาน 4 ขั้นตอน:

  1. สร้าง Object ใหม่ว่างเปล่า
  2. ผูก __proto__ ของ Object ใหม่ ไปที่ Constructor.prototype
  3. เรียก Constructor Function โดยให้ this ชี้ไปที่ Object ใหม่
  4. คืนค่า Object ใหม่ (เว้นแต่ Constructor return Object อื่น)

ตัวอย่างโค้ด

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>New Operator</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result { font-size: 20px; font-weight: 500; color: blueviolet; }
  </style>
</head>
<body>
  <h1>New Operator ใน JavaScript</h1>
  <div class="result"></div>
  <br />
  <button class="Btn">คลิกที่นี่</button>
  <h3>คลิกปุ่มด้านบนเพื่อสร้าง object person1 จาก Person constructor</h3>
  <script>
    const resEle = document.querySelector(".result");
    const BtnEle = document.querySelector(".Btn");
    
    function Person(name, age, designation) {
      this.name = name;
      this.age = age;
      this.designation = designation;
    }
    
    const person1 = new Person("Rohan Sharma", 19, "student");
    
    BtnEle.addEventListener("click", () => {
      resEle.innerHTML = `person1.name = ${person1.name}<br>`;
      resEle.innerHTML += `person1.age = ${person1.age}<br>`;
      resEle.innerHTML += `person1.designation = ${person1.designation}<br>`;
    });
  </script>
</body>
</html>

เกิดอะไรขึ้นถ้าไม่ใช้ new?

function Person(name) {
  this.name = name;
}

const p1 = Person("John"); // ไม่ใช้ new
console.log(p1);           // undefined
console.log(window.name);  // "John" - this ชี้ไป window! (non-strict mode)

การป้องกัน: new.target (ES6)

function Person(name) {
  if (!new.target) {
    throw new Error("ต้องใช้ new สร้าง Person");
  }
  this.name = name;
}

ผลลัพธ์

แสดง properties ของ person1: name, age, designation