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

Class trong JavaScript là gì?

class

Class là loại function, nhưng dùng từ khóa 'class' thay vì 'function', property gán trong constructor(). constructor() chạy mỗi lần khởi tạo object.

Ví dụ 1

<html> <body> <p id="class"></p> <script> class Company { constructor(branch) { this.name = branch; } } myComp = new Company("Tutorialspoint"); document.getElementById("class").innerHTML = myComp.name; </script> </body> </html>

Kết quả

Tutorialspoint

Ví dụ 2

<html> <body> <script> class Company { constructor(branch) { this.name = branch; } } myComp = new Company("Rk enterprises"); document.write(myComp.name); </script> </body> </html>

Kết quả

Rk enterprises

Đặc điểm class ES6:

  • Syntax sugar cho prototype-based inheritance
  • Hoisting: class không được hoisted (khác function declaration)
  • Strict mode mặc định
  • Method không cần từ khóa function
  • Hỗ trợ extends, super, static, get/set