How to write maintainable object-oriented JavaScript code

Source: Internet
Author: User

Being able to write maintainable object-oriented JavaScript code can save money and make you very popular. Don't believe me? It's possible that you or someone else will come back one day to reuse your code. If you can try to make this experience less painful, you can save a lot of time. The Earth knows that time is money. In the same way, you will get his preference for helping someone save a headache. But before we start exploring how to write maintainable object-oriented JavaScript code, let's take a quick look at what is object-oriented. If you already know the concept of object-oriented, you can skip the next section directly.

What is object-oriented?

Object-oriented programming primarily represents real-world objects through code. To create an object, you first need to write a "class" to define it. The class can represent almost everything: accounts, employees, navigation menus, cars, plants, ads, drinks, etc. Each time you create an object, you instantiate an object from the class. In other words, an instance of a class is created as an object. In fact, objects are often used when dealing with more than one kind of thing. In addition, you can do a good job simply by having a functional program. objects are essentially containers of data. Therefore, in an Employee object, you may want to store the employee number, name, entry date, title, salary, seniority, and so on. Objects also include functions that process data (also called "Methods"). method is used as a medium to ensure the integrity of the data and to convert the data before it is stored. For example, a method can receive a date in any format and then convert it to a normalized format before storing it. Finally, classes can inherit other classes as well. Inheritance allows you to reuse the same code in different classes. For example, bank accounts and video store accounts can inherit a basic account class that includes personal information, account opening dates, division information, and so on. Each can then define its own transactions or data structures and methods such as loan processing.

Warning: JavaScript Object-oriented is not the same

In the previous section, you outlined the basics of classic object-oriented programming. The classic is that JavaScript doesn't follow these rules. In contrast, JavaScript classes are written as functions, and inheritance is done through prototypes. Prototype inheritance basically means using a prototype property to implement an object's inheritance, rather than inheriting the class from the class.

Instantiation of an object

The following are examples of object instantiation in javascript:

Define Employee class function employee (NUM, fname, lname) {    this.getfullname = function () {        return fname + "" + lname;< c2/>}};//instantiation of the Employee object var john = new Employee ("4815162342", "John", "Doe"), Alert ("The employee's full name is" + john.ge Tfullname ());

Here, there are three key points to note:

1. The first letter of the "class" function name should be capitalized. This indicates that the purpose of the function is to be instantiated instead of being called as a general function.

2. The new operator is used when instantiating. If you omit new and just call a function, there are a lot of problems.

3. Because Getfullname is assigned to the This operator, it is publicly available, but fname and lname are not. Closures generated by the employee function give getfullname to fname and lname, but are still private to other classes.

Prototype inheritance

Here is an example of JavaScript inheritance in plain form:

Define Human class function Human () {    this.setname = function (fname, lname) {        this.fname = fname;        This.lname = lname;    }    This.getfullname = function () {        return this.fname + "" + This.lname;    }} Defines the Employee Class function employee (NUM) {    this.getnum = function () {        return num;    }};/ /Let employee inherit Human class Employee.prototype = new Human ();//Instantiate Employee object var john = new Employee ("4815162342");    John.setname ("John", "Doe"), Alert (John.getfullname () + "' s employee number is" + john.getnum ());

This time, the human class created contains all the common attributes of mankind--I also put fname and lname in, because not only employees have names, everyone has names. The human object is then assigned a value to its prototype property.

Implementing code reuse through inheritance

In the previous example, the original employee class was decomposed into two parts. All common human attributes were moved to the human class, and the employee was then inherited to human. In this case, the attributes inside the human can be used by other objects, such as student (student), client (customer), Citizen (Citizen), Visitor (tourist), and so on. Now you may notice that this is a good way to split and reuse code. When working with human objects, you only need to inherit human to use existing properties without having to re-create each of the different objects one by one. In addition, if you want to add a "middle name" attribute, just add one more time, those who inherit the Human class can be used immediately. Instead, if we just want to give an object a "middle name" attribute, we add it directly to that object without adding it to the Human class.

Public (common) and private (private)

For the next topic, I want to talk about public and private variables in the class. Depending on how the data is processed in the object, the data is processed as private or public. Private properties do not necessarily mean that others cannot access them. Maybe it's just a method that needs to be used.

Read-only

Sometimes, you just want to have a value when creating an object. Once created, you don't want someone else to change the value. To do this, you can create a private variable that is assigned a value when instantiated.

function Animal (type) {    var data = [];    data[' type '] = type;    This.gettype = function () {        return data[' type '];}    } var fluffy = new Animal (' dog '); Fluffy.gettype (); Back to ' dog '

In this example, a local array of data is created in the animal class. When the animal object is instantiated, a value of type is passed and the value is placed in the data array. Because it is private, the value cannot be overwritten (the animal function defines its scope). Once an object is instantiated, the only way to read the type value is to call the GetType method. Because GetType is defined in animal, GetType can be entered into data with the closure generated by the animal. In this case, the type of the object can be read but cannot be changed.

It is important to note that "read-only" technology cannot be used when an object is inherited. After inheritance is performed, each instantiated object shares those read-only variables and overrides their values. The simplest solution is to convert a read-only variable in a class to a public variable. But you have to keep them private and you can use the techniques mentioned in Philippe in the comments.

Public (publicly)

Of course there are times when you want to read and write the value of a property. To achieve this, you need to use this operator.

function Animal () {    this.mood = ';} var fluffy = new Animal (); fluffy.mood = ' happy '; fluffy.mood; Back to ' happy '

This time the animal class exposes a property called mood, which can be read and written freely. Similarly, you can assign a function to a public property, such as the GetType function in the previous example. Just be careful not to assign a value to GetType, otherwise you'll ruin it.

Fully private

Finally, you may find that you need a fully privatized local variable. In this case, 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 ();

Write a flexible API

Now that we've talked about the creation of classes, in order to keep pace with the changes in product requirements, we need to keep the code out of date. If you have already done some projects or long-term maintenance of a product, then you should know that demand is changing. This is an indisputable fact. If you don't think so, your code will be doomed to ruin before it's written. You may suddenly need to animate the contents of the tab, or you need to get the data through an AJAX call. Although it is unlikely to predict the future accurately, it is quite possible to write code flexibly for future contingencies.

Saner parameter list

You can make your code forward-looking when you design a list of parameters. A parameter list is the main point of contact for someone else to implement your code, and it can be problematic if it is not designed properly. 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 a middle name parameter after you post the code, because of the order problem, you have to go up at the end of the list. This makes work awkward. It will be very difficult if you do not assign a value to each parameter. For example:

var ara = new Person (1234, "Ara", "Pehlivanian", "514-555-1234", NULL, NULL, NULL, "1976-05-17");

The more neat and flexible way to manipulate the parameter list is to use this pattern:

function person (employeeId, data) {};

There is a first parameter because this is required. The rest is mixed in with 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. Not only that, objects are not in a particular order, so it's easy to add a middle name parameter where it's convenient:

var ara = new Person (1234, {    fname: "Ara",    mname: "Chris",    lname: "Pehlivanian",    Tel: "514-555-1234", C8/>dob: "1976-05-17"});

The code inside the class is not important, because the value inside can be indexed to access the question:

function person (employeeId, data) {this.fname = data[' fname '];};

If data[' fname ' Returns a value, then he is set. Otherwise, it is not set, and there is no loss.

Allow code to be embedded

As time goes by, product requirements may have more requirements for your class's behavior. This behavior is not related to the core function of your class. It is also possible that the only implementation of a class is to make the contents of this tab panel grayed out when you get external data for another tab in the Panel of one tab. You might want to put these functions inside the class, but they don't belong there. The responsibility of the tab strip is the Management tab. Animations and getting data are different from each other and must be separated from the Code of the tab strip. The only way to get your tab strip, however, is to exclude the additional functionality from being allowed to embed the behavior in the code. In other words, create events to hook them up to critical moments in your code, such as Ontabchange, aftertabchange, onshowpanel, aftershowpanel, and so on. In that case, they can easily hook up with your Onshowpanel event and write a processor that turns the panel content gray, so you're happy. JavaScript libraries make it easy enough to do this, but it's not that hard to write yourself. Here is an example of using yui 3.

<script type= "Text/javascript" src= "Http://yui.yahooapis.com/combo?3.2.0/build/yui/yui-min.js" ></script ><script type= "Text/javascript" >    YUI (). Use (' event ', function (Y) {       function TabStrip () {            This.showpanel = function () {this.fire (' onshowpanel ');//Display panel code this.fire (' Aftershowpanel ');};        }        ; Let TabStrip have the ability to inspire common event        y.augment (TabStrip, y.eventtarget);        var ts = new TabStrip ();        Create a common time processor        ts.on (' Onshowpanel ', function () {            //What to do before the presentation panel) for this instance of TabStrip        });        Ts.on (' Onshowpanel ', function () {            //other things to do before the presentation panel        });        Ts.on (' Aftershowpanel ', function () {            //What to do after the display panel        });        Ts.showpanel ();    }); </script>

This example has a simple TabStrip class, which has a Showpanel method. This method fires two events, Onshowpanel and Aftershowpanel. This ability is achieved by expanding the class with Y.eventtarget. Once made, we instantiate a TabStrip object and assign a bunch of processors to it. This is a common code used to handle instances of the unique behavior while avoiding confusion about the current class.

Summarize

If you're going to reuse code, whether it's on the same Web page, the same site, or cross-project operations, consider packaging and organizing it in a class. Object-oriented JavaScript is a natural way to help achieve better code organization and code reuse. Beyond that, you can make sure your code is flexible enough to last a long time after you've written your code. Writing reusable JavaScript code can save you, your team and your company's time and money. This will definitely make you very popular.

How to write maintainable object-oriented JavaScript code

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.