How to Write maintainable object-oriented JavaScript code

Source: Internet
Author: User
Writing maintainable object-oriented JavaScript code not only saves money, but also makes you very popular. Believe it? Maybe you or someone else will come back to reuse your code one day. If you try to make this experience less painful, you can save a lot of time. Everyone on Earth knows... SyntaxHighlighter. all ();

Writing maintainable object-oriented JavaScript code not only saves money, but also makes you very popular. Believe it? Maybe you or someone else will come back to reuse your code one day. If you try to make this experience less painful, you can save a lot of time. Everyone on Earth knows that time is money. In the same way, you will gain a preference for someone because it saves them a headache. However, before you start to explore how to write maintainable object-oriented JavaScript code, let's take a quick look at what object-oriented code is. If you already know the concept of object-oriented, you can skip the next section.
What Is Object-Oriented?
Object-Oriented Programming mainly uses code to represent real objects in the real world. To create an object, you must first define it by writing a "class. Classes can represent almost everything: Accounts, employees, navigation menus, cars, plants, advertisements, drinks, and so on. Each time an object is created, an object is instantiated from the class. In other words, it is to create a class instance as an object. In fact, objects are usually used to process more than one similar thing. In addition, you only need simple functional programs to do well. Objects are essentially data containers. Therefore, in an employee object, you may need to store employee numbers, names, employment dates, titles, salaries, qualifications, and so on. Objects also include functions that process data (also called methods "). Methods are used as media to ensure data integrity and convert data before storage. For example, a method can receive dates in any format and convert them to a standard format before they are stored. Finally, the class can inherit other classes. Inheritance allows you to reuse the same code in different classes. For example, both a bank account and an audio and video store account can inherit a basic account type, including personal information, account opening date, and branch information. Then, each user can define their own transaction or loan processing data structures and methods.
Warning JavaScript object-oriented is different
The previous section outlines the basic knowledge of classical object-oriented programming. The typical reason is that JavaScript does not follow these rules. On the contrary, JavaScript classes are written as functions, while inheritance is implemented through prototype. Prototype inheritance basically means using prototype attributes to inherit objects, rather than inheriting classes from classes.
Object Instantiation
The following is an example of Object Instantiation in JavaScript:
// Define the Employee class
Function Employee (num, fname, lname ){
This. getFullName = function (){
Return fname + "" + lname;
}
};
 
// Instantiate the Employee object
Var john = new Employee ("4815162342", "John", "Doe ");
Alert ("The employee's full name is" + john. getFullName ());
Here, there are three important points to note:
1. The first letter of the "class" function name must be in uppercase. This indicates that the function is instantiated rather than called as a common function.
2. The new operator is used during instantiation. If new is omitted and function calling is performed only, many problems may occur.
3 because getFullName is specified to this operator, it is public and available, but fname and lname are not. The closure generated by the Employee function gives the getFullName entry to fname and lname, but it is still private to other classes.
Prototype inheritance
The following is an example of original type inheritance in JavaScript:
// Define the Human class
Function Human (){
This. setName = function (fname, lname ){
This. fname = fname;
This. lname = lname;
}
This. getFullName = function (){
Return this. fname + "" + this. lname;
}
}
 
// Define the Employee class
Function Employee (num ){
This. getNum = function (){
Return num;
}
};
// Let the Employee inherit the Human class
Employee. prototype = new Human ();
 
// Instantiate the Employee object
Var john = new Employee ("4815162342 ");
John. setName ("John", "Doe ");
Alert (john. getFullName () + "'s employee number is" + john. getNum ());
This time, the created Human class contains all the common attributes of humans-I also put fname and lname, because not only employees have names, but all people have names. Then assign the Human object to its prototype attribute.
Code reuse through inheritance
In the previous example, the original Employee class is divided into two parts. All common Human attributes are moved to the Human class, and the Employee inherits the Human class. In this way, attributes in Human can be used by other objects, such as Student, Client, Citizen, and Visitor. Now you may have noticed that this is a good way to separate and reuse code. When processing a Human object, you only need to inherit the Human object to use the existing attributes, instead of re-creating each different object. In addition, if you want to add an "Intermediate name" attribute, you only need to add it once. Those that inherit the Human class can be immediately used. Instead, if we just want to add the "Intermediate name" attribute to an object, we can add it directly to that object without adding it to the Human class.
1. Public and Private)
Next, I want to talk about public and private variables in the class. Data is processed as private or public based on the data processing methods in the object. Private attributes do not necessarily mean that others cannot access them. It may only be required for a method.
● Read-only
Sometimes, you just want to have a value when creating an object. Once created, no one else needs to change the value. To do this, you can create a private variable and assign values to it during instantiation.
Function Animal (type ){
Var data = [];
Data ['type'] = type;
This. getType = function (){
Return data ['type'];
}
}
 
Var fluffy = new Animal ('Dog ');
Fluffy. getType (); // return 'Dog'
In this example, a local array data is created in the Animal class. When an Animal object is instantiated, a type value is passed and placed in the data array. Because it is private, this value cannot be overwritten (the Animal function defines its range ). Once the object is instantiated, the only way to read the type value is to call the getType method. Because getType is defined in Animal, with the closure generated by Animal, getType can be imported into data. In this way, the type of the object can be read but cannot be changed.
It is very important that when an object is inherited, the "read-only" technology cannot be used. After inheritance is executed, each instantiated object shares the read-only variables and overwrites their values. The simplest solution is to convert the read-only variables in the class to public variables. However, you must keep them private. You can use the technology mentioned in the comment by Philip.
● Public)
Of course, sometimes you want to read or write the value of an attribute at will. To achieve this, you need to use the this operator.
Function Animal (){
This. mood = '';
}
 
Var fluffy = new Animal ();
Fluffy. mood = 'Happy ';
Fluffy. mood; // return 'Happy'
This time, the Animal class discloses a mood attribute that can be read and written at will. Similarly, you can specify a function to a public attribute, for example, the getType function in the previous example. Do not assign values to getType. Otherwise, you will destroy it.
Completely private
Finally, you may find that you need a fully private local variable. In this way, you can use the same pattern as in the first example without creating a public method.
Function Animal (){
Var secret = "You'll never know! "
}
 
Var fluffy = new Animal ();
2. Write flexible APIs
Since we have already talked about the creation of classes, we need to keep the code out of date to keep pace with changes in product requirements. If you have already done some projects or have maintained a product for a long time, you should know that the demand is changing. This is an indisputable fact. If you don't think so, your code will be ruined before it is written. You may suddenly need to make the content in the tab into an animation, or you need to call Ajax to obtain data. Although it is unlikely to accurately predict the future, it is completely possible to write code flexibly for future needs.
● Saner parameter list
The code can be proactive when designing the parameter list. The parameter list is the main touchpoint for others to implement your code. If it is not well designed, it will be very problematic. You should avoid the following parameter list:
Function Person (employeeId, fname, lname, tel, fax, email, email2, dob ){
};
This class is very fragile. If you want to add an intermediate name parameter after you release the code, you have to add it at the end of the list due to order problems. This makes your work awkward. If you do not assign values to each parameter, it will be very difficult. For example:
Var ara = new Person (1234, "Ara", "Pehlivanian", "514-555-1234", null, null ");
You can use this mode to make the operation parameter list more clean and flexible:
Function Person (employeeId, data ){
};
The first parameter is required. The rest will be mixed in the object so that it can be used flexibly.
Var ara = new Person (1234 ,{
Fname: "Ara ",
Lname: "Pehlivanian ",
Tel: "514-555-1234 ",
Dob: "1976-05-17"
});
The beauty of this model is that it is easy to read and highly flexible. Note that fax, email, and email2 are completely ignored. In addition, the object has no specific order, so it is very easy to add an intermediate name parameter wherever it is convenient:
Var ara = new Person (1234 ,{
Fname: "Ara ",
Mname: "Chris ",
Lname: "Pehlivanian ",
Tel: "514-555-1234 ",
Dob: "1976-05-17"
});
The code in the class is not important, because the values in the class can be accessed through indexes:
Function Person (employeeId, data ){
This. fname = data ['fname'];
};
If data ['fname'] returns a value, it is set. Otherwise, it is not set and there is no loss.
● Make code embedded
As time passes, product requirements may have more requirements for your behaviors. This behavior is not related to your core functions. It may also be the only Implementation of the class. For example, when obtaining external data of another tab on the panel of a tab, the content in this tab panel is grayed out. You may want to put these functions in the class, but they do not belong to it. The responsibility of a tab bar is to manage tabs. Animation and data retrieval are completely different. They must also be separated from the tab bar code. The only way to get your tab entries out of those additional features is to allow behavior to be embedded into the code. In other words, create events to hook them to critical moments in your code, such as onTabChange, afterTabChange, onShowPanel, and afterShowPanel. In that case, they can easily hook up with your onShowPanel event and write a processor that will gray the panel content, so that everyone will be happy. The JavaScript library allows you to easily do this, but it is not that difficult to write it yourself. The following is an example of using YUI 3.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.