Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //---------------------------------------
- //--- Code tự nhiên ---------------------
- //---------------------------------------
- class Account {
- username: string;
- password: string;
- register (username: string, password: string){
- // Kiểm tra username và password có hợp lệ hay không rồi mới cho đăng ký
- // Ví dụ như username không bị trùng, password thì phải trên 8 ký tự chẳng hạn
- if (checkValidUsername(username) && checkValidPassword(password)) {
- this.username = username;
- this.password = password;
- }
- }
- authenticate(username: string, password: string){
- return this.username === username && this.password === password;
- }
- }
- let batman = new Account();
- // Có đến 2 cách để thiết lập username, password cho người dùng.
- // Nếu dev hên mà dùng cách 1 thì không sao
- batman.register('Robinson', 'iloveu');
- // Còn đen mà dùng cách này để thiết lập username password thì teo lúc nào không biết.
- batman.username = 'Robinson'; // Không kiểm tra được tính hợp lệ của username và password
- batman.password = 'iloveu';
- //---------------------------------------
- //--- Áp dụng encapsulation vào----------
- //---------------------------------------
- class Account {
- private _username: string;
- private _password: string;
- register (username: string, password: string){
- // Kiểm tra username và password có hợp lệ hay không rồi mới cho đăng ký
- // Ví dụ như username không bị trùng, password thì phải trên 8 ký tự chẳng hạn
- if (checkValidUsername(username) && checkValidPassword(password)) {
- this._username = username;
- this._password = password;
- }
- }
- authenticate(username: string, password: string){
- return this._username === username && this._password === password;
- }
- }
- let superman = new Account();
- // Code chặt chẽ thế này thì chỉ làm sao mà ra bugs =)))
- superman.register('Robinson', 'iloveu');
Add Comment
Please, Sign In to add comment