Are comments 100% safe on all the major environmen

2019-05-01 19:47发布

问题:

Are comments literally just stripped out of your source before parsing, or can they count as linebreaks and disrupt continuity in certain contexts?

'foo'.replace(/f/, 'b') //f->b
     .replace(/o/, 'a') //o->a
     .replace(/o/, 'r') /*o->r*/ ;

'foo'.replace(/x/, /*matches "x"*/ 'y');

var foo = ( true !== false ) ? // bikeshed
          'bar' : /*if they're equal, which they won't be, we'll want 'baz'*/ 'baz';

You know, cause they say whitespace is "safe" and "insignificant" or whatever, but we all know there are exceptions to that. Are comments actually safe?

回答1:

They're ignored during parsing, if they were stripped out before parsing, the parser would need to scan the input twice.

However, the LineTerminator at the end of the line is not considered to be part of the single-line comment; it is recognised separately by the lexical grammar and becomes part of the stream of input elements for the syntactic grammar. This point is very important, because it implies that the presence or absence of single-line comments does not affect the process of automatic semicolon insertion

ES5 Specification for comments.

The source code is tokenised as if the comments didn't exist.



回答2:

Yes, comments are safe.

(That being said, I've seen some broken server-side HTML minifiers that don't know what inline JavaScript is, and removes all of the line breaks. A comment beginning with // comments out the entire script.)