Getter và Setter (set, get)
Getter và Setter là interceptor cho property (có ý nghĩa như truy cập, gán giá trị, theo dõi).
Cách khai báo như sau:
tsclassHuman {private_name : string;public constructor(name : string) {this._name =name ;}// Khai báo Gettergetname (): string {return this._name ;}// Khai báo Settersetname (name : string) {this._name =name ;}}consthuman = newHuman ("");// Sử dụng Setterhuman .name = `Nguyen Van An`;// Sử dụng Getterconsole .log (human .name );
tsclassHuman {private_name : string;public constructor(name : string) {this._name =name ;}// Khai báo Gettergetname (): string {return this._name ;}// Khai báo Settersetname (name : string) {this._name =name ;}}consthuman = newHuman ("");// Sử dụng Setterhuman .name = `Nguyen Van An`;// Sử dụng Getterconsole .log (human .name );
Khác với method, khi gọi getter/setter không cần dùng ().
ts// Getterconsole .log (human .name ); // Cách sử dụng Getter đúngThis expression is not callable because it is a 'get' accessor. Did you mean to use it without '()'? Type 'String' has no call signatures.6234This expression is not callable because it is a 'get' accessor. Did you mean to use it without '()'? Type 'String' has no call signatures.console .log (human .()); // Lỗi: human.name is not a function name // Setterhuman .name = "Nguyen Van An"; // Cách sử dụng Setter đúngThis expression is not callable. Type 'String' has no call signatures.2349This expression is not callable. Type 'String' has no call signatures.human .("Nguyen Van An"); name
ts// Getterconsole .log (human .name ); // Cách sử dụng Getter đúngThis expression is not callable because it is a 'get' accessor. Did you mean to use it without '()'? Type 'String' has no call signatures.6234This expression is not callable because it is a 'get' accessor. Did you mean to use it without '()'? Type 'String' has no call signatures.console .log (human .()); // Lỗi: human.name is not a function name // Setterhuman .name = "Nguyen Van An"; // Cách sử dụng Setter đúngThis expression is not callable. Type 'String' has no call signatures.2349This expression is not callable. Type 'String' has no call signatures.human .("Nguyen Van An"); name
Getter
Cú pháp của Getter:
tsget tên(): kiểu_dữ_liệu {// Xử lý nếu cầnreturn giá_trị;}
tsget tên(): kiểu_dữ_liệu {// Xử lý nếu cầnreturn giá_trị;}
Getter không thể có tham số. Phải chỉ định giá trị trả về.
Setter
Cú pháp của Setter:
tsset tên(biến: kiểu_dữ_liệu) {// Xử lý nếu cần// Xử lý lưu giá trị}
tsset tên(biến: kiểu_dữ_liệu) {// Xử lý nếu cần// Xử lý lưu giá trị}
Setter bắt buộc phải có đúng một tham số. Không thể chỉ định giá trị trả về.