简体   繁体   中英

Javascript - Why Functions Vs Code Blocks are Needed Sometimes

Okay, so the only way to explain this is with an example. In javascript you can do something such as:

if(condition) {

}

The { and } are used to identify a code block. But in some cases such as this:

window.onload = function() {

}

You need the function() included. Why can't it just be:

window.onload {

}

Why the need for function() ? Also, I thought functions all have a name associated with them, and when that name is called the function runs, but why in this case is there a function with no associated name?

if , for , while , try , catch , etc. are all statements that modify the following statement. For example, an if ( condition ) statement will only execute the following statement if the condition expression evaluates to true (or is truthy ). A block statement is a special type of statement that is used to group multiple statements together, allowing an if statement to apply to a larger section of your code.

However, window.onload = function() { } is an expression —an entirely different construct. It's an assignment expression consisting of three parts, an assignment operator ( = ) an expression representing the value to assign (in this case a function expression ) and a reference to a variable or property to assign that value to ( window.onload ).

Note also that there is a difference between a function expression as mentioned above and a function statement , as this can often lead to some confusion. In both constructs, the curly brackets are required around the body (unlike in an if statement).

{ and } (also called "curly brackets") are punctuators , they are mostly used to denote a block of code, but have other uses.

Code blocks are statements that are conditionally executed and are used in various productions of the grammar, such as to enclose the statements related to an if statement :

if (condition) {
  // statements to execute if condition is true
}

function bodies in declarations:

function foo() {
  // statements in function body
} 

and expressions:

var foo = function () {
  // statements in function body
}

also in for , while and do loops, switch and with statements, and so on. Curly brackets are also used in object initialisers (aka object literals ):

var obj = {name: 'foo', age: 42};

and probably lots of other parts of the grammar that don't come to mind right now.

Edit

So having said all that, time for the questions:

Why the need for function() ?

To indicate that the following code block is the body of a function, not some other production.

Also, I thought functions all have a name associated with them,

For a function expression, a name is optional. The name is only available inside the function (except for certain versions of IE which had a bug that made the name global) to allow for recursive calling:

// Function expression
var foo = function bar() {
            // In here, call as bar or foo
          };

// Everywhere else, call as foo    
foo();

and when that name is called the function runs, but why in this case is there a function with no associated name?

Function expressions are usually assigned to a variable and that name is used to call them. They are also passed in function calls, executed immediately or assigned to object properties where they can be called using normal property accessor syntax:

var obj = {};
obj.foo = function(){alert('My name is foo')};
obj.foo(); 

Function declarations create a variable in the scope of the declaration with the function name and the function object created from the body is assigned to that variable. Function declarations are processed before any code is executed.

There is quite a bit written about function expressions vs function declarations, see Named function expressions demystified and A closer look at expression closures .

You think about Javascript (and maybe programming languages in general) the wrong way.

First of all, the if is a statement, a language struct that controlls the program flow. It is designed to look like if (condition) code . window.onload is a variable. window is an object here, which can "contain" other variables ( onload in this case), accessable with that dot notation.

In JavaScript you can assign almost anything to a variable, since everything is basically the same. This is confusing and totally awesome at the same time imo.

You assigned a function, which works via the given syntax new function(params) {code} . You could habe also done window.onload = 5 or window.onload = {a: 5, b: "foo", c: ["bar", "baz"]} . (But that would cause runtime errors, because your browser fails to "run" that. Same error as if you'd try to run var a = 5; a(); )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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