คีย์เวิร์ด new ใน JavaScript เป็น โอเปอเรเตอร์สร้างอินสแตนซ์ (Instance) ของ User-defined Object Type หรือ Built-in Constructor Function ทำงาน 4 ขั้นตอน:
- สร้าง Object ใหม่ว่างเปล่า
- เชื่อม
__proto__ของ Object ใหม่ ไปยังConstructor.prototype - เรียก Constructor Function ด้วย
thisชี้ไป Object ใหม่ - ส่งคืน Object ใหม่ (เว้นแต่ Constructor Return Object อื่น)
ไวยากรณ์
new Constructor([arguments])
ตัวอย่าง: สร้าง Object แบบ Custom
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
// Constructor Function
function Department(employee, department, technology) {
this.employee = employee;
this.department = department;
this.technology = technology;
}
// ใช้ new สร้าง Instance
var dept = new Department("David", "Programming", "C++");
document.getElementById("demo").innerHTML =
dept.employee + " is working on " + dept.technology + " technology.";
</script>
</body>
</html>
ตัวอย่าง Built-in Constructors
// Object
var obj = new Object(); // หรือ {}
var arr = new Array(1,2,3); // หรือ [1,2,3]
var date = new Date(); // วันที่ปัจจุบัน
var regex = new RegExp("\\d+"); // Regular Expression
var error = new Error("Message");
// Function (ไม่ควรใช้)
var func = new Function("a", "b", "return a + b");
เกิดอะไรขึ้นถ้าไม่ใช้ new?
function User(name) {
this.name = name;
}
var u1 = new User("John"); // this = instance ใหม่ ✓
var u2 = User("Jane"); // this = window (global) ✗ ระบบไม่แจ้งเตือน!
console.log(window.name); // "Jane" - ปนเปื้อน Global Scope
Strict Mode ("use strict") จะทำให้ this เป็น undefined และโยน Error แทน
การ Return ค่าใน Constructor
function Test() {
this.a = 1;
return { b: 2 }; // Return Object อื่น -> new จะส่งค่านี้แทน
}
var t = new Test();
console.log(t.a); // undefined
console.log(t.b); // 2
function Test2() {
this.a = 1;
return 42; // Return Primitive -> new ข้ามไป ส่ง instance ปกติ
}
var t2 = new Test2();
console.log(t2.a); // 1
ES6 Classes (Syntactic Sugar)
class Department {
constructor(employee, department, technology) {
this.employee = employee;
this.department = department;
this.technology = technology;
}
}
var dept = new Department("David", "Programming", "C++");
ข้อควรระวัง
- ชื่อ Constructor ควรขึ้นต้นด้วยตัวใหญ่ (PascalCase) ตาม Convention
- Arrow Function ไม่สามารถใช้เป็น Constructor ได้ (
new () => {}Error) - บาง Built-in ไม่ต้องใช้ new:
Symbol(),BigInt()