Example of how to use a command object instead of a switch statement _javascript tips

Source: Internet
Author: User
Tags case statement

It has been said that a really good program is no if. Else, of course, switch is not as good as if. Else JS specification inside is prohibit to use switch.

The Command object is the perfect solution to the problem.

Referring to a foreign blog:

JavaScript has good control flow statements, which are often wrapped in curly braces. One exception: Switch ... case statement. Switch ... the strange thing about the case is that you have to add a keyword break at the end of each of the cases to prevent process control from crossing into the next statement. Crossing refers to the way that many cases are executed, and when the expected break is not met, control is automatically handed to the next case. However, just as with semicolons and curly braces, you are likely to inadvertently forget to write a break, and when this happens, later troubleshooting is more painful, because the statement itself is correct. So, pairing the case ... break is a good habit.
We usually say that JavaScript has elegant object literals and top-level functions that make a particular method query very simple. The object created for the method query, which we call the active object (Action object) or the command object, is used in many software design patterns, including powerful and useful command patterns.

Instance:

Copy Code code as follows:

Switch method
function Testswitch (name) {
Switch (name) {
Case ' 1 ':
return ' hack ';
Break
Case ' 2 ':
Return ' slash ';
Break
Case ' 3 ':
return ' run ';
Break
Default
return false;
Break
}
}
Using Command objects
function Testfn (name) {
var names = {
' 1 ': function () {
return ' hack ';
},
' 2 ': function () {
Return ' slash ';
},
' 3 ': function () {
return ' run ';
}
};
if (typeof Names[name]!== ' function ') {
return false;
}
return Names[name] ();
}
Test results
var result1 = Testswitch (' 1 ');
var result2 = testfn (' 2 ');
Console.info (RESULT1, RESULT2);

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.