Home  >  Article  >  Web Front-end  >  Example of writing using command object instead of switch statement_javascript skills

Example of writing using command object instead of switch statement_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:12:101415browse

Someone once said that a truly good program does not have if..else. Of course, switch is not as good as if..else. The use of switch is prohibited in the JS specification.

The command object perfectly solves this problem.

Quote from a foreign blog:

JavaScript has good control flow statements, which are often wrapped in curly braces. There is one exception: the switch … case statement. The strange thing about switch ... case is that you must add the break keyword at the end of each case to prevent flow control from passing into the next case statement. Traversal refers to the method of executing multiple cases. When the expected break is not encountered, control is automatically handed over to the next case. However, just like semicolons and braces, you may inadvertently forget to write break. When this happens, troubleshooting later will be more painful because the statement itself is correct. Therefore, it is a good practice to write case ... break in pairs.
We usually say that JavaScript has elegant object literals and top-level functions, which make specific method queries very simple. The objects created for method queries are called action objects or command objects, and are used in many software design patterns, including the powerful and useful command pattern.

Example:

Copy code The code is 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;
}
}
//Use command object
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);
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn