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

Getter và Setter trong class JavaScript

Class cho phép dùng getter và setter. Rất hữu ích khi muốn xử lý giá trị trước khi trả về hoặc gán. Dùng từ khóa get và set.

Ví dụ

<html> <body> <p id="method"></p> <script>    class Company {       constructor(brand) {          this.Compname = brand;       }       get name() {          return this.Compname;       }       set name(x) {          this.Compname = x;       }    }    myName = new Company("Tutorialspoint");    document.getElementById("method").innerHTML = myName.Compname; </script> </body> </html>

Kết quả

Tutorialspoint

Giải thích:

  • get name(): Gọi như property obj.name (không có dấu ngoặc)
  • set name(x): Gán như property obj.name = 'value'
  • Cho phép validation, tính toán, logging khi get/set
  • Thường dùng với property private (prefix # hoặc _)

Ví dụ thực tế:

class User {
  #password = '';
  get password() { return '********'; }
  set password(val) { 
    if (val.length >= 8) this.#password = val;
    else throw new Error('Password too short');
  }
}