神刀安全网

Semicolons matter

When your code’s intention is ambiguous, your JavaScript engine will attempt to fill in the gaps. If there are multiple potential intentions, your engine will tend to assume you meant to do the right thing. Multi-line statements are supported, omitting semicolons is not, and therefore if the case is ambiguous your engine will assume you meant to write a multi-line statement.

Take the following example:

function Logger() { }  // Log something to the console at a specified level Logger.prototype.log = function(level) {   console[level || 'log'].apply(console, [].slice.apply(arguments, 1)); }  // Sugar functions for Logger.log ['info', 'warn', 'error'].forEach(function(level) {   Logger.prototype[level] = function () {     return this.log.apply(this, [level].concat(Array.from(arguments)));   } });

What will happen when this is run? Did you spot the missing semicolon? Here’s how v8 sees it:

Logger.prototype.log =    function() { }['info', 'warn', 'error'].forEach(function() { });

Which is perfectly valid code; it is the equivalent of:

function foo() { } Logger.prototype.log = foo['error'].forEach(function() { });

Be unambiguous with your code. If you’re ending a statement, use a semicolon.

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Semicolons matter

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮