课程: JavaScript Practice: Object-Oriented Programming

Solution: User/admin class with private properties - JavaScript教程

课程: JavaScript Practice: Object-Oriented Programming

Solution: User/admin class with private properties

- [Instructor] We'll create the user object using JavaScript class syntax. The user class constructor takes two parameters, username and password. Since password is a private variable, we'll prepend the property name with a hash symbol. Additionally, we'll declare password as a private variable above the constructor. (keyboard clacking) Now we can create the resetPassword function. This takes one parameter, newPassword. We don't want the user to be able to directly alter the password, so we'll create another private function that will do the updating. We'll call our private function updatePassword. It will take the newPassword parameter as well. To make this function private, we'll prepend a hash symbol to the function name like we did with our password variable. (keyboard clacking) Back inside our resetPassword function, we can call our private updatePassword function and pass a new password. Then we'll return the string, Your password has been updated. (keyboard clacking) Now we can create the admin class. Since admin is a special type of user, we'll inherit from the user class with the extends keyword. Admin also takes a username and password. We need to pass these values up the prototype chain to the user class. To do this, we'll call the super function, and pass username and password through. We'll also add a variable to the admin constructor called isAdmin. We'll set this property to true. (keyboard clacking) Lastly, we need to create our deleteUser function. It takes one parameter, a string containing the username to delete. This function just returns a template literal stating that the user we passed into the function has been deleted. (keyboard clacking) When we run our code, we can see all of our tests are passing.

内容