Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/460.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 何时使用分号_Javascript - Fatal编程技术网

Javascript 何时使用分号

Javascript 何时使用分号,javascript,Javascript,特别是在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() { }; } 有人能

特别是在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(){};

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

这是自JavaScript运动以来的个人风格问题:

当程序从左到右解析时,遇到任何语法生成都不允许的标记(称为违规标记),然后在违规标记之前自动插入分号,如果。。。至少有一个行终止符将有问题的标记与前一个标记分隔开来

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

一贯的做法是:

this.init = function(x, y) {
   this.x = x;
   this.y = y;
};
是否在SO中讨论过的问题。

来自:

1-JavaScript错误-首先使用调用返回42的函数 第二个函数作为参数,则数字42被“调用” 导致错误

2-你很可能会得到一个“不”的答案 属性尝试调用时在运行时出现“未定义”错误 x[ffVersion]isIE

3-除非调用resultOfOperation(),否则将调用die NaN和THINGS_TO_EAT被分配die()的结果


.事实上,我会说答案是你很善于观察;我在编码时的挑剔也会给第一个加上分号。也就是说,我可以理解为什么有些人不想包含它(我所知道的所有JS解析器都会很容易自动处理),这是因为编写代码的人是不一致的。如果
}
后面的任何空格后面的下一个字符以
this.init
开头(
this.init
将是匿名函数调用的结果。这在谷歌代码风格指南中的“有几个地方缺少分号特别危险:”下,但是你的回答听起来好像这是预期的风格。@BenjaminGruenbaum他的第一个例子我认为并不少见(在构造函数中定义方法,并在末尾使用IIFE作为初始化方法)。我也偶然发现了这一点,花了很长时间才找到错误所在。在某种程度上,我想这仍然是一个风格的问题,但我也认为应该鼓励人们不要太依赖ASI,而只是学习在哪里放置分号。@basilikum哦,我完全同意,我总是使用分号,我总是用JSHint来填充代码。这不是我要评论的。我个人不喜欢ASI。@BenjaminGruenbaum那么我可能误读了你的评论。很抱歉。
// 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();