Are comments 100% safe on all the major environments?

江枫思渺然 提交于 2019-12-07 04:58:33

问题


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.)



来源:https://stackoverflow.com/questions/12659020/are-comments-100-safe-on-all-the-major-environments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!