简体   繁体   English

在javascript中声明和定义函数

[英]declaring and defining functions in javascript



I have a doubt regarding functions(objects) in javascript. 我对javascript中的函数(对象)有疑问。

I have 2 pieces of code like, 我有两段代码,比如

    var a= function(){
    console.log('abc')
     }


and

     var a= (function(){
     console.log('abc')
     })


what is the difference between these two>> 这两者有什么区别>>
thanx:) 感谢名单:)

There is no difference now, but if you add another parenthesis () after second function it will run function without invocation. 现在没有区别,但是如果你在第二个函数之后添加另一个括号(),它将运行函数而不调用。

 var a= (function(){
     console.log('abc')
     })()

it will print 'abc' straightaway 它将直接打印'abc'

There is no difference. 没有区别。 You have a function expression, and you can put any number of parentheses around an expression. 你有一个函数表达式,你可以在表达式周围放置任意数量的括号。

Just as this: 就像这样:

a = 42;

is the same as this: 与此相同:

a = (42);

and this: 还有这个:

a = (((((42)))));

There is no practical difference. 没有实际的区别。 They will both result in an anonymous function being assigned to a . 它们都会导致将匿名函数分配给a

The first is a " simple assignment ". 第一个是“ 简单的任务 ”。 In the second, the parentheses are acting as a " grouping operator ", which does one thing: 在第二个中,括号充当“ 分组运算符 ”,它做了一件事:

The production PrimaryExpression : ( Expression ) is evaluated as follows: 生产PrimaryExpression:(Expression)的计算方法如下:

  • Return the result of evaluating Expression. 返回评估Expression的结果。 This may be of type Reference. 这可能是参考类型。

So the grouping operator will return the function contained within it, and assign it to a , just like the first example. 因此,分组运算符将返回其中包含的函数,并将其分配给a ,就像第一个示例一样。

There is a difference. 它们是有区别的。

( and ) constitute a grouping. (和)构成一个分组。 A grouping can only contain an expression, thus any function inside it will be an expression and not a declaration. 分组只能包含表达式,因此其中的任何函数都将是表达式而不是声明。

Since ECMA specifies that a function declaration must always have a function name, and a function expression may omit it, you will be able to do the following 由于ECMA指定函数声明必须始终具有函数名称,并且函数表达式可以省略它,因此您将能够执行以下操作

(function() {});

while the following declaration is not valid 而以下声明无效

function() {};

It won't matter that often, but still... Read this in-depth article for more: http://kangax.github.com/nfe/ 这通常没关系,但仍然......阅读这篇深入的文章了解更多信息: http//kangax.github.com/nfe/

As has been said, the two examples you've given are essentially the same. 如前所述,您给出的两个例子基本相同。

This question has a lot more information contained in the answers regarding parentheses usage, might be worth your time to spin through! 这个问题有关于括号使用的答案中包含的更多信息,可能值得您花时间去讨论!

Why are parenthesis used to wrap a javascript function call? 为什么括号用于包装javascript函数调用?

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

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