Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Toán tử new trong JavaScript

Đị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

  1. Tạo object rỗng mới.
  2. Gán __proto__ = Constructor.prototype.
  3. Gọi Constructor với this = object mới.
  4. 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;
}