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

Tại sao 'class' là từ khóa dành riêng (reserved word) trong JavaScript

class là từ khóa dành riêng (reserved word) trong JavaScript từ lâu, nhưng chỉ thực sự có ý nghĩa cú pháp từ ES6 (ES2015). Trước đó, nó được dự trữ cho tương lai.

Lịch sử

  • ES1-ES5: class là future reserved word – không dùng được làm tên biến/hàm, nhưng không có chức năng.
  • ES6 (2015): Giới thiệu class syntax – syntactic sugar cho prototype-based inheritance.
  • ES2022+: Thêm private fields (#field), static blocks, extends null.

Danh sách từ khóa dành riêng (Reserved Words)

Theo ECMAScript spec, bao gồm:


// Đang dùng (keywords)
break, case, catch, class, const, continue, debugger, default, delete, do, else,
export, extends, false, finally, for, function, if, import, in, instanceof, new,
null, return, super, switch, this, throw, true, try, typeof, var, void, while, with,
yield, let, static, enum, implements, interface, package, private, protected, public

// Future reserved (strict mode)
await, implements, interface, package, private, protected, public, static

Cú pháp Class (ES6)


// Class declaration
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  greet() {
    console.log(`Xin chào, tôi là ${this.name}`);
  }
  
  static species() { return "Human"; }
}

// Class expression
const Animal = class {
  constructor(name) { this.name = name; }
};

// Inheritance
class Student extends Person {
  constructor(name, age, studentId) {
    super(name, age); // Gọi constructor cha
    this.studentId = studentId;
  }
  
  study() { console.log(`${this.name} đang học`); }
}

Class bên dưới là Function


class Person {}
typeof Person;           // "function"
Person.prototype.constructor === Person; // true
// Class KHÔNG tạo kiểu dữ liệu mới – vẫn là function + prototype

Tại sao dự trữ từ trước?

  • Tránh code cũ dùng var class = ... bị lỗi khi nâng cấp engine.
  • Cho phép thiết kế syntax sau này mà không breaking change.
  • Các từ khóa khác tương tự: enum, extends, super, const, export, import.

Lưu ý

  • Không dùng class làm tên biến, hàm, property: var class = 1 → SyntaxError.
  • Trong non-strict mode, một số từ khóa cũ (như class trước ES6) có thể dùng làm property: obj.class = 1 – nhưng KHÔNG KHUYẾN NGHỊ.
  • Strict mode ("use strict") cấm dùng future reserved words làm identifier hoàn toàn.