Định nghĩa
new Constructor() tạo instance mới của đối tượng do hàm constructor định nghĩa.
Quy trình new
- Tạo object rỗng mới.
- Gán
__proto__=Constructor.prototype. - Gọi
Constructorvớithis= object mới. - Trả về object mới (trừ khi constructor return object khác).
Ví dụ
<script>
function Department() {
this.name = "Department";
}
var dept = new Department();
dept.employee = "David";
dept.technology = "C++";
document.write(dept.employee + " works on " + dept.technology);
</script>
Class syntax (ES6) – Khuyên dùng
class Department {
constructor() {
this.name = "Department";
}
}
const dept = new Department();
Quên new – Cạm bẫy
function Foo() { this.x = 1; }
var a = Foo(); // không new
// this = window (sloppy) hoặc undefined (strict)
// a = undefined
// window.x = 1 (ô nhiễm global!)
Giải pháp: Dùng new.target kiểm tra hoặc class (báo lỗi nếu thiếu new).
new.target (ES2015)
function Foo() {
if (!new.target) throw new Error("Must use new");
this.x = 1;
}