Background
[wp_ad_camp_1]
I must admit I used to dislike JavaScript and UI development. First, I related JavaScript to Web UI design at which I am very not good at. I do not have an artistic side when it comes to programming in general. Second, I felt JavaScript was a second-class language. As I have worked on UI/JavaScript-related projects for the last seven months, I realized the need to learn more, if not impossible to master, JavaScript.
Software Environment
- Any modern web browser
JavaScript file
Create a Student.js file and place it under js/classes. In JavaScript, you reuse the function construct to represent classes (or new reference types). Note the use of “this” within the Student function (actually it is a constructor now). To add behavior to your class, you can write functions within it or use the prototype construct as shown below.
[wp_ad_camp_2]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | function Student() { this.lastName = null; this.firstName = null; this.middleName = null; this.studentId = null; } Student.prototype.getLastName = function() { return this.lastName; } Student.prototype.setLastName = function(lastName) { this.lastName = lastName; } Student.prototype.getFirstName = function() { return this.firstName; } Student.prototype.setFirstName = function(firstName) { this.firstName = firstName; } Student.prototype.getMiddleName = function() { return this.middleName; } Student.prototype.setMiddleName = function(middleName) { this.middleName = middleName; } Student.prototype.getStudentId = function() { return this.studentId; } Student.prototype.setStudentId = function(studentId) { this.studentId = studentId; } |
HTML file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <script src="js/classes/Student.js" type="text/javascript"></script> </head> <body> <script> var studentObject = new Student(); studentObject.setLastName('San Gabriel'); studentObject.setFirstName('Karl'); studentObject.setMiddleName('*** Confidential ***'); document.write(studentObject.getFirstName() + ' ' + studentObject.getMiddleName() + ' ' + studentObject.getLastName()); </script> </body> </html> |
Sample Output
[wp_ad_camp_3]