Writing to maintain object-oriented JavaScript code [translation]_js Object-oriented

Source: Internet
Author: User
Tags closure data structures switch case try catch

Writing maintainable object-oriented (OO) JavaScript would save you, and make your popular. Don ' t believe me? Odds are that either you or someone else would come back and work with your code. Making as painless an experience as possible'll save time, which we all know equates to. It'll also win your favor of those for whom you just saved a headache. But before we dive into writing maintainable Oo JavaScript, let's just take a quick look at what Oo are all about. If you are know already about OO, feel free to skip the next section.

What is OO?
Object-oriented programming basically represents physical, Real-world objects that you want to work with the in code. In the order to create objects, your need to the define them by writing what ' s called a class. Classes can represent pretty much anything:accounts, employees, navigation menus, vehicles, plants, advertisements, drink S, etc ... Then, every time you want to create an object to work with, you instantiate one from a class. In the other words, your create an instance of a class which gives your an object to work with. In fact, the best time to being using objects is when you'll be dealing with more than one of anything. Otherwise, a simple functional program would likely do just as. Objects are essentially containers for data. So in the case of a Employee object, you might store their employee number, name, start date, title, salary, seniority, E Tc... Objects also include functions (called methods) to handle that data. Methods are used as intermediaries to ensure data integrity. They ' re also used to transform data before storing it. For example, Alpha could receive a date in the arbitrary format then convert it to a standardized format before It. Finally, classes can also inherit from the other classes. Inheritance allows you to reuse code across different types of classes. For example, both bank account and video store account classes could inherit to a base account class which would provide fields for profiles information, account creation date, branch information, etc ... Then, each would define its own transactions or rentals handling data structures and methods.

Warning:javascript OO is different
The previous section I outlined the basics of classical object-oriented programming. I say classical because JavaScript doesn ' t quite follow rules. Instead, JavaScript classes are actually written as functions and inheritance is prototypal. Prototypal inheritance basically means that rather than classes inheriting to classes, they inherit from objects using T He prototype the property.

Object Instantiation
Here's an example of the object instantiation in JavaScript:

Copy Code code as follows:

Define the Employee class
function Employee (num, fname, lname) {
This.getfullname = function () {
return fname + "" + lname;
}
};
Instantiate an Employee object
var john = new Employee ("4815162342", "John", "Doe");
Alert ("The employee ' s full name is" + john.getfullname ());

There are three important things to:

I uppercased the "class" function. That's important distinction lets people know that it's for instantiation and is called as a normal function.
I Use the new operator when instantiating. Leaving it out would simply call the function and result in problems.
Though Getfullname is publicly available because it's assigned to the This operator, fname and LName are. The closure created by the Employee function gives Getfullname access to fname and lname while allowing them to remain PRI Vate from everyone else.
Prototypal inheritance
Now, here's a example of Prototypal inheritance in JavaScript:
Copy Code code as follows:

Define 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 Employee inherit from Human
Employee.prototype = new Human ();

Instantiate an Employee object
var john = new Employee ("4815162342");
John.setname ("John", "Doe");
Alert (John.getfullname () + "' Employee number is" + john.getnum ());

This time, I ' ve created a Human class which contains properties common to Humans--i moved fname and lname there all Humans, not just employees have names. I then extended the Employee class by assigning a Human object to its prototype property.

Code reuse through inheritance
In the previous example, I split the original Employee class in two. I moved out all of the properties common to all humans into a Human class, and then caused Employee to inherit from Human. That's way, the properties laid out in Human could is used by other objects such as Student, Client, Citizen, Visitor, etc. . As you could have noticed by now, this is a great way to compartmentalize and reuse code. Rather than recreating all of those properties to every single type of object where we ' re dealing with a human being, we Can just use what ' s already available by inheriting from Human. What ' s more, if we ever wanted to add a-like say, middle name, we ' d do it once and it would immediately Ble to the Everyone inheriting from Human. Conversely, if we are wanted to add a middle the Name property to just one object, we could does it directly in ' that object ins Tead of adding it to Human.

Public and Private
I ' d like to touch on the subject of public and private variables in classes. Depending on what your ' re doing with the ' data in an object, your ' ll want to either make it private or public. A private property doesn ' t necessarily mean which people won ' t have access to it. You could just want them to go through one of your methods.

read-only
Sometimes, you are want a value defined once at the moment of the object is created. Once created, you don ' t want anyone changing that value. In the order to does this, the create a private variable and have its value set on instantiation.

Copy Code code as follows:

function Animal (type) {
var data = [];
data[' type ' = type;
This.gettype = function () {
Return data[' type '];
}
}

var fluffy = new Animal (' dog ');
Fluffy.gettype (); Returns ' Dog '

In this example, I create a local array called data within the Animal class. When a Animal object is instantiated, a value for type is passed and set in the data array. This value can ' t is overwritten as it ' s private (the Animal function defines its scope). The only way to read the type value once a object is instantiated be to call the GetType method I ' ve explicitly expo Sed. Since GetType is defined inside Animal, it has access to data by virtue of the closure created by Animal. This way, people can read the object ' s type but it.

It's important to the "read-only" technique would not be work when this is inherited from. Every object instantiated after the inheritance is performed'll share those read-only variables and overwrite each other ' s values. The simplest solution is to convert the read-only variables into the class to public ones. If However, you are must keep them private, you can employ the technique of out by pointed in the Philippe.

Public
There are times however, which you'll want to is able to read and write a property ' s value at'll. To do so, you are need to expose using the ' this operator.
Copy Code code as follows:

function Animal () {
This.mood = ';
}

var fluffy = new Animal ();
Fluffy.mood = ' happy ';
Fluffy.mood; Returns ' Happy '

This time we Animal class exposes a property named mood which can is written to and read at'll. You can equally assign a function to public properties like the GetType function in the previous example. Just be careful not to assign a value to a property like GetType or you'll destroy it with your value.

completely Private
Finally, you are might find yourself in scenarios where you are need a local variable that ' s completely private. In this case, you can use the same pattern as the ' example ' and just ' not ' create a for people to access I T.
Copy Code code as follows:

function Animal () {
var secret = "You ll never know!"
}
var fluffy = new Animal ();

writing a flexible API
Now so we ' ve covered class creation, we need to future proof them in order to keep up with product requirement changes. If you have done any project work, or maintained a product long-term, your know that requirements change. It ' s a fact of life. To the Doom your code to obsolescence before it ' s even written. You could suddenly have to animate your tab content, or have it fetch data via a Ajax call. Though It's impossible to truly predict the future, it's possible to write code that's flexible enough to be reasonably f Uture proof.

saner Parameter Lists
One place where future-proofing can do is designing parameter lists. They ' re the main point of the contacts for people implementing your code and can is problematic if not. Designed. What you want to avoid are parameter as this:
Copy Code code as follows:

function person (employeeId, fname, lname, tel, fax, email, email2, DOB) {
};

This class is very fragile. If you are want to add a middle name parameter once your ' ve released the Code, you ' re going to have to doing it at the very end of The list since order matters. That's makes it awkward to work with. It also makes it difficult to work with if don ' t have values for each parameter. For example:
Copy Code code as follows:

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

A Cleaner, more flexible way of approaching parameter lists-to-use-pattern:
Copy Code code as follows:

function person (employeeId, data) {
};

The parameter is there because it ' s required. The rest is lumped together in a object which can be very flexible to work with.
Copy Code code as follows:

var ara = new Person (1234, {
FName: "Ara",
LName: "Pehlivanian",
Tel: "514-555-1234",
DOB: "1976-05-17"
});

The beauty of this are that it's both easy to read and highly flexible. How to Fax, email and email2 were completely left. Also, since objects aren ' t order specific, adding a middle name parameter be as easy as throwing it in wherever it ' s conve Nient:
Copy Code code as follows:

var ara = new Person (1234, {
FName: "Ara",
Mname: "Chris",
LName: "Pehlivanian",
Tel: "514-555-1234",
DOB: "1976-05-17"
});

The code inside the class doesn ' t care because the values get accessed by index like so:
Copy Code code as follows:

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

If data[' fname '] returns a value, it gets set. Otherwise, it doesn ' t, and nothing breaks.

Make It pluggable
As time goes on, the product requirements might demand additional behavior from your. Yet often times, that behavior has absolutely no to do with your class ' s core functionality. It ' s also likely that it's a requirement for only one implementation of the class, like fading in the contents of one tab ' The S panel while fetching external the data for another. You are tempted to put those abilities inside your class, but they don ' t belong there. A tab Strip ' s responsibility is to manage tabs. Animation and data fetching are two completely separate things and should be kept the tab strip ' s code. The only way to future proof your tab strip and keep all that extra functionality, are to external allow to people plug Aviors into your code. In the other words, the allow people to hook into the key moments in your code by creating events like Ontabchange, Aftertabchange, on Showpanel, Aftershowpanel and so on. That way, they can easily hook into your Onshowpanel event, write a handler that fades In the contents of that panel and everyone is happy. JavaScript libraries allow to do this easily enough, but it's not too hard to work it out on your. Here's a simple example using YUI 3.
Copy Code code as follows:

<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 ');

Code to show the panel
This.fire (' Aftershowpanel ');
};
};

Give TabStrip the ability to fire custom events
Y.augment (TabStrip, y.eventtarget);
var ts = new TabStrip ();

Set up custom event handlers to this instance of TabStrip
Ts.on (' Onshowpanel ', function () {
Do something before showing panel
});
Ts.on (' Onshowpanel ', function () {
Do something else before showing panel
});
Ts.on (' Aftershowpanel ', function () {
Do something after showing panel
});

Ts.showpanel ();
});
</script>

This is example has a simple TabStrip class with a Showpanel method. The method fires two events, Onshowpanel and Aftershowpanel. It's given the ability to does by augmenting the class with Y.eventtarget. Once that's done, we instantiate a TabStrip object and assign a bunch an event handlers to it. This is we custom code for handling this instance's unique behavior without messing with the actual class.

Summary
If you are reusing code either on the same page, website or across multiple projects, consider packaging and Organizin G it in classes. Object-oriented JavaScript lends itself naturally to better code organization and reuse. What ' s more, with a little forethought, can make sure this your code is flexible enough to stay in use long ve written it. Writing reusable, Future-proof JavaScript would save you, your team and your company time and money. That's sure to make your popular.

This book is better suited to have a certain Javascipt code base, but need to improve the code of the standardization of developers to see

A personal gain:

1. Standardization of writing code

@ writing should be reasonably indented

When the @ line is too long, remember to wrap the line and note that the next line indents

@ blank line, for each logical branch, annotate the module

@ The name of the variable in hump form, uniform canonical naming

@=== and = = Use to pay attention to the use of = = = must not use = =, asynchronous we want to develop with the development of a good data type

@ Double brackets should have appropriate spaces to improve reading

@ Switch case to indent and end with break

Separation of 2.CSS and Html,js

In HTML, it is best not to inline, to use the external form, display inline is available

Do not inline events in the label, do the JS event and label separation

In the script with CSS, preferably with classname. Do not write some style directly. Do a good job of CSS and JS separation

3.try catch

Catch errors, benefits can see where the problem, can be found in time to reduce debugging time, to take full advantage of the error mechanism in the component

4. New and detached configuration file config

Configure some constants and values, or some message text information

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.