简体   繁体   English

我什么时候应该在 javascript 中的函数后放一个分号?

[英]When should I put a semicolon after a function in javascript?

My examples:我的例子:

(First example area is the function assignment with semicolon) (第一个示例区域是带分号的函数赋值)

function makeImage() {
var canvas = document.getElementById("tshirtCanvas");
**canvas.onclick = function () {
    window.location = canvas.toDataURL('image/png');
};**
}

vs对比

window.onload = function() {
    var button = document.getElementById("previewButton");
    button.onclick = previewHandler;


    makeImage();
}

I thought I had the hang of when to use it, and when not to, but I guess I do not.我以为我知道何时使用它,何时不使用它,但我想我没有。 Thanks.谢谢。

You should put a semi-colon after a function when you use it as a value:当您将其用作值时,您应该在函数后放置一个分号:

 var fn = function () {};
 blarg.fn = function () {};
 doStuffWith(function () {});

If you're just declaring a named function by itself, you don't need the semicolon:如果您只是自己声明一个命名函数,则不需要分号:

function doFoo() {}

Note that in the top cases, you don't always have to have a semicolon, but you should put one anyway.请注意,在最常见的情况下,您不必总是分号,但无论如何都应该放一个。

Function expressions get semicolons (normal line ending rules apply).函数表达式使用分号(适用正常的行结束规则)。 Function declarations do not.函数声明没有。

http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/ http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/

If you are assigning a function to a property , you should put a semicolon.如果要将函数分配给属性,则应放置分号。 So you could put a semicolon for the window.onload because you are assigning a function to the onload property of the window.因此,您可以为 window.onload 放置一个分号,因为您正在为窗口的 onload 属性分配一个函数。 The semicolon isn't required, but I highly recommended you put it to prevent confusion.分号不是必需的,但我强烈建议您使用分号以防止混淆。

window.onload = function() {
    init();
    doSomethingElse();
};

From the MDN Docs.来自MDN 文档。

Your function declaration doesn't need it after.您的函数声明之后不需要它。 Just if you are calling it.只要你调用它。

function doThis(args){
getterMethod(args);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM