This article describes the two methods that are commonly used to define functions in JS. Although the results of Function calls defined in the two methods are the same, there are still differences between them, I believe this article will surely help you gain some benefits.
JS is a very common method for defining functions.
We all know that Javascript has two Function-defining methods that are very common.
For example
- functiona(){alert("a")}
-
- vara=function(){alert("a")}
Although the results of function calls defined by the two methods are the same, there are still differences between them. For example, if we want to redefine a (), and the new method must inherit all the methods in a () and perform other extensions. The difference between the two methods is obvious.
1. First, create a temporary variable to store ()
- varb=a;
-
Then, redefine ()
Method 1:
- functiona(){
- b();
- alert("ok");
- }
Method 2:
- a=function(){
- b();
- alert("ok");
- }
This is something you can try to find. The first way to redefine a () will cause a stack overflow error. In the second method, the script executed by a () is successfully retained, and alert prompts "a" "OK", indicating that () is redefined.
Here we can clearly distinguish between the two methods. The order of definition is different.
First, the function a was not re-defined at the beginning and the function itself was executed in it.
In the second way, a = function () is not executed here. Code a in the function has been redefined. So the definition here is valid.