Discussion on whether to add brackets when calling functions in js

  • 2021-07-06 09:49:07
  • OfStack

In fact, it can be summed up as follows:

A function must be parenthesized as long as it is called for execution. At this point, the function () is actually equal to the return value of the function. Of course, some have no return value, but they have already performed the behavior in the function body. This is fundamental, that is, if you put parentheses, it means that the function body code will be executed.

Without parentheses, the function name is used as a pointer to the function, which is used to pass parameters. At this time, the result of the function is not obtained, because the function body code will not be run. It just passes the address location of the function body, so that it can be found and executed when necessary.

Therefore, most of the time, we all use the reason without brackets. This is also due to the two meanings of parentheses, because parentheses are "function call operators", which is equivalent to executing such a function, so the problems will be understood after being understood.

In addition: except that there are no brackets on both sides, You can also put parentheses on both sides to make a copy of the function. Instead of executing a function, If there are no parentheses on the left and parentheses on the right, In fact, it is equivalent to generating a property instead of a method. When calling, only the attribute name or function name is used, and there is no need to use the function call operator parentheses, because it is equivalent to an attribute. Of course, it can also be called in the way of function call, plus parentheses. For example, if it is written as person. sayHello = sayHi (), you can directly use person. sayHello or person. sayHello () when calling sayHello, both of which achieve the same effect.

Baidu knows the answer:

A function must be parenthesized as long as it is called for execution. At this point, the function () is actually equal to the return value of the function. Of course, some have no return value, but they have already performed the behavior in the function body. This is fundamental, that is, if you put parentheses, it means that the function body code will be executed.

Without parentheses, the function name is used as a pointer to the function, which is used to pass parameters. At this time, the result of the function is not obtained, because the function body code will not be run. It just passes the address location of the function body, so that it can be found and executed when necessary.


Related articles: