|
| 1 | +##自动分号插入 |
| 2 | + |
| 3 | +尽管 JavaScript 有 C 的代码风格,但是它**不**强制要求在代码中使用分号,实际上可以省略它们。 |
| 4 | + |
| 5 | +JavaScript 不是一个没有分号的语言,恰恰相反上它需要分号来就解析源代码。 |
| 6 | +因此 JavaScript 解析器在遇到由于缺少分号导致的解析错误时,会**自动**在源代码中插入分号。 |
| 7 | + |
| 8 | + var foo = function() { |
| 9 | + } // 解析错误,分号丢失 |
| 10 | + test() |
| 11 | + |
| 12 | +自动插入分号,解析器重新解析。 |
| 13 | + |
| 14 | + var foo = function() { |
| 15 | + }; // 没有错误,解析继续 |
| 16 | + test() |
| 17 | + |
| 18 | +自动的分号插入被认为是 JavaScript 语言**最大**的设计缺陷之一,因为它*能*改变代码的行为。 |
| 19 | + |
| 20 | +### 工作原理 |
| 21 | + |
| 22 | +下面的代码没有分号,因此解析器需要自己判断需要在哪些地方插入分号。 |
| 23 | + |
| 24 | + (function(window, undefined) { |
| 25 | + function test(options) { |
| 26 | + log('testing!') |
| 27 | + |
| 28 | + (options.list || []).forEach(function(i) { |
| 29 | + |
| 30 | + }) |
| 31 | + |
| 32 | + options.value.test( |
| 33 | + 'long string to pass here', |
| 34 | + 'and another long string to pass' |
| 35 | + ) |
| 36 | + |
| 37 | + return |
| 38 | + { |
| 39 | + foo: function() {} |
| 40 | + } |
| 41 | + } |
| 42 | + window.test = test |
| 43 | + |
| 44 | + })(window) |
| 45 | + |
| 46 | + (function(window) { |
| 47 | + window.someLibrary = {} |
| 48 | + })(window) |
| 49 | + |
| 50 | +下面是解析器"猜测"的结果。 |
| 51 | + |
| 52 | + (function(window, undefined) { |
| 53 | + function test(options) { |
| 54 | + |
| 55 | + // 没有插入分号,两行被合并为一行 |
| 56 | + log('testing!')(options.list || []).forEach(function(i) { |
| 57 | + |
| 58 | + }); // <- 插入分号 |
| 59 | + |
| 60 | + options.value.test( |
| 61 | + 'long string to pass here', |
| 62 | + 'and another long string to pass' |
| 63 | + ); // <- 插入分号 |
| 64 | + |
| 65 | + return; // <- 插入分号, 改变了 return 表达式的行为 |
| 66 | + { // 作为一个代码段处理 |
| 67 | + foo: function() {} |
| 68 | + }; // <- 插入分号 |
| 69 | + } |
| 70 | + window.test = test; // <- 插入分号 |
| 71 | + |
| 72 | + // 两行又被合并了 |
| 73 | + })(window)(function(window) { |
| 74 | + window.someLibrary = {}; // <- 插入分号 |
| 75 | + })(window); //<- 插入分号 |
| 76 | + |
| 77 | +> **注意:** JavaScript 不能正确的处理 `return` 表达式紧跟换行符的情况, |
| 78 | +> 虽然这不能算是自动分号插入的错误,但这确实是一种不希望的副作用。 |
| 79 | +
|
| 80 | +解析器显著改变了上面代码的行为,在另外一些情况下也会做出**错误的处理**。 |
| 81 | + |
| 82 | +###前置括号 |
| 83 | + |
| 84 | +在前置括号的情况下,解析器**不会**自动插入分号。 |
| 85 | + |
| 86 | + log('testing!') |
| 87 | + (options.list || []).forEach(function(i) {}) |
| 88 | + |
| 89 | +上面代码被解析器转换为一行。 |
| 90 | + |
| 91 | + log('testing!')(options.list || []).forEach(function(i) {}) |
| 92 | + |
| 93 | +`log` 函数的执行结果**极大**可能**不是**函数;这种情况下就会出现 `TypeError` 的错误,详细错误信息可能是 `undefined is not a function`。 |
| 94 | + |
| 95 | +###结论 |
| 96 | + |
| 97 | +建议**绝对**不要省略分号,同时也提倡将花括号和相应的表达式放在一行, |
| 98 | +对于只有一行代码的 `if` 或者 `else` 表达式,也不应该省略花括号。 |
| 99 | +这些良好的编程习惯不仅可以提到代码的一致性,而且可以防止解析器改变代码行为的错误处理。 |
| 100 | + |
0 commit comments