JS maintainability Code

Source: Internet
Author: User

Recently read a JS book called "JavaScript Advanced Program Design" in the inside learned a lot of things, is a good book, it is worth a look.

Decoupling Css/javascript

Element.style.color= "Red";

Element.style.backgroundcolor= "Blue";

The way CSS and JavaScript are too close, we should write:

Element.classname= "edit";

CSS style and JS code completely separate.

Optimize again:

var cssname={

Css1: "Edit",

}

Element.classname=cssname.css1;

2. Decoupling application logic/event handlers

function Handlekeypress (event) {

Event=eventutil.getevent (event);

if (event.keycode==13) {

var target=eventutil.gettarget (event);

var value=5*parentint (Target.value);

if (value>10) {

Document.getelement ("Error-msg"). style.display= "Block";

}

}

};

Written:

function Validatevalue (value) {

Value=5*parseint (value);

if (value>10) {

Document.getelement ("Error-msg"). style.display= "Block";

}

};

function Handlekeypress (event) {

Event=eventutil.getevent (event);

if (event.keycode==13) {

var target=eventutil.gettarget (event);

}

};

3. Avoid global Volume:

var name= "Ncihoals"

function Sayname () {

}

Written:

var myapplication={

Name: "Nicholas",

Sayname:function () {

}

}

The concept of the JS namespace:

Creating global objects

var wrox={};

To create a namespace:

wrox.projs={};

Append all the variables used to the Wrox

wrox.projs.eventutil={};

The main purpose of this is to be able to coexist with other JS files on the same page without duplicate names.

3. Avoid comparisons with null:

function Sortarry (values) {

if (values!=null) {//Avoid

Values.sort (Comparator);

}

}

function Sortarry (values) {

if (values instanceof Arry) {//Recommended

Values.sort (Comparator);

}

}

JS maintainability 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.