2

特别是在 JavaScript 中,什么时候使用分号,什么时候不使用。

这是一个示例代码片段;

function Drawable() {
   this.init = function(x, y) {
      this.x = x;
      this.y = y;
   }

   this.speed = 0;
   this.canvasWidth = 0;
   this.canvasHeight = 0;

   this.draw = function() {
   };
}

有人可以告诉我为什么

this.init = function(x,y) {}

但是不以分号结尾

this.draw = function(){};

在上面的代码片段中是否以分号结尾?

4

2 回答 2

8

这是个人风格问题,因为 JavaScript 支持自动分号插入。:

当程序从左到右解析时,遇到任何语法生成都不允许的标记(称为违规标记)时,如果...由至少一个LineTerminator与前一个标记分开。

第一个没有以分号结尾,因为上面的代码不一致。

一致的方式是:

this.init = function(x, y) {
   this.x = x;
   this.y = y;
};

你是否应该使用它们的问题之前已经在 SO 中讨论过。

于 2013-06-26T18:33:56.500 回答
1

来自Google JavaScript 样式指南

// 1.
MyClass.prototype.myMethod = function() {
  return 42;
}  // No semicolon here.

(function() {
  // Some initialization code wrapped in a function to create a scope for locals.
})();


var x = {
  'i': 1,
  'j': 2
}  // No semicolon here.

// 2.  Trying to do one thing on Internet Explorer and another on Firefox.
// I know you'd never write code like this, but throw me a bone.
[normalVersion, ffVersion][isIE]();


var THINGS_TO_EAT = [apples, oysters, sprayOnCheese]  // No semicolon here.

// 3. conditional execution a la bash
-1 == resultOfOperation() || die();

1 - JavaScript 错误 - 首先以第二个函数作为参数调用返回 42 的函数,然后“调用”数字 42 导致错误。

2 - 当它试图调用 x[ffVersion]isIE 时,您很可能会在运行时收到“未定义中没有此类属性”错误。

3 - die 被调用,除非 resultOfOperation() 是 NaN 并且 THINGS_TO_EAT 被分配 die() 的结果。

于 2013-06-26T18:38:00.230 回答