I know there are several ways to define functions in javascript. Two of the most common ones are:
(1) Add function (A, B) {return a + b; } (2) var add = function (a, b) {return a + b; }
I am comfortable with the idea of ​​a function as an object, which can be passed like any other variable, so I understand that (2)
What it is doing is creating a function and will say addition
(assuming this is in the global scope, hence the add
is a global variable) function called . But then what if I use (1)
? I already know that it makes a difference in execution order: if I use (1)
then I'll add code in the code before the code add ()
Where is added by ()
, but if I use (2)
then I can add to
my function Must be assigned before I can start referring to ()
.
is a shortcut for (1)
only (2)
, although in another C-style languages ​​we define a point "below" What is the use on which it is used? Or is it a different type of function internally? Which is more in Javascript's "soul" (if that word is not very obscure)? Can you limit yourself to one or the other, and if so what?
It looks like you 1 ( 1) and (2) are already aware of the main features. Also note that (1) still has a local variable which has a function value named add
, such as (2):
function (hello) {Alert ('hello world'); } Console.log (types of Hello); // print "function" set timeout (hello, 1000); // You can still pass the function as arguments, even when using the // function declarations.
Another notable point is that function declarations (1) should not be used to define conditional work (such as If
statement), because as you mentioned, they automatically went to the top of the area with the JavaScript translator 2 . This is usually referred to as .
The way JavaScript looks more approachable, I like to use the function expression (2). For a more authoritative opinion, lists the work announcements (1) in the "Bad Parts" chapter in their popular 2 .
Also known as Function Statement (see comments below). 2 can actually handle
statement in some browsers task announcements (see the comments below again). 3 - Appendix B: Page 113.
Comments
Post a Comment