Object-oriented JavaScript
From a language perspective, object-oriented programming and object-oriented JavaScript language are definitely not modern things; JavaScript was originally designed as a thorough object-oriented language. However, as JavaScript has "gradually evolved" in its use and acceptance, programmers in other languages (such as Ruby, Python, and Perl, etc.) noticed it and began to introduce their programming patterns into JavaScript.
The appearance and internal operation of object-oriented JavaScript code are different from other languages with object capabilities. In Chapter 2 I will discuss in depth all aspects that make it so unique, and here, let’s first look at some basic things to experience the initial feeling of writing modern JavaScript code. Examples of two object constructors in program 1-1 demonstrate a simple object collocation that can be used in school courses.
Program 1-1. Object-oriented JavaScript statement of courses and course sheets
//Lecture class constructor
//Use two string parameters, name and teacher
function Lecture( name, teacher ) {
//Save them as local properties of objects
= name;
= teacher;
}
//The method of class Lecture generates a string that displays the course information
= function(){
return + " is teaching " + ;
};
//Constructor of class Schedule
//Use an array of records as parameter
function Schedule( lectures ) {
= lectures;
}
//The method of class Schedule is used to construct a string describing the course sheet
= function(){
var str = "";
//Travel through each course and accumulate to form an information string
for ( var i = 0; i < ; i++ )
str += [i].display() + " ";
return str;
};
You may have seen from the code of Program 1-1 that most of the basics of object-oriented principles exist throughout it, but they are organized in a different way than other more common object-oriented languages. You can create object constructors and methods and access object properties. Program 1-2 shows an example of using the above two classes in an application.
Program 1-2. Provide users with a list of courses
//Create a new class object, stored in the variable mySchedule
var mySchedule = new Schedule([
//Create an array of course objects,
//As the only parameter to the class schedule (original text is Lecture here, suspected to be a typo) object
new Lecture( "Gym", "Mr. Smith" ),
new Lecture( "Math", "Mrs. Jones" ),
new Lecture( "English", "TBD" )
]);
// A dialog box pops up to display the information of the class schedule
alert( () );
With the acceptance of JavaScript by programmers, the use of well-designed object-oriented code is becoming increasingly popular. Throughout this book, I'll try to show different object-oriented JavaScript code snippets that I think are best illustrated with code design and implementation.
Previous page123456Next pageRead the full text