From e89c7ea3f70909221a5fd0dbeb712eb38f218273 Mon Sep 17 00:00:00 2001 From: JasonHomeWorkstationUbuntu Date: Wed, 13 Jan 2021 23:18:41 +1100 Subject: [PATCH] Finished Chapter 8.1.2 Function Expressions --- notes/chap8_functions.md | 33 +++++++++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/notes/chap8_functions.md b/notes/chap8_functions.md index 88d6695..15baf3b 100644 --- a/notes/chap8_functions.md +++ b/notes/chap8_functions.md @@ -20,7 +20,7 @@ JS function definitions can be nested within other functions ### 8.1.1 Function Declarations -**Function declaration** = `function` keyword + Identifier as function name + `(param1, param2, ...)` + `{JS statements as function body}` +**Function declaration (函数声明)** = `function` keyword + Identifier as function name + `(param1, param2, ...)` + `{JS statements as function body}` * `return` causes function to stop executing and return computed value to caller * if body has no `return`, value of function is `undefined` @@ -53,6 +53,31 @@ function factorial(x) { ### 8.1.2 Function Expressions -Function Expression (FE 函数表达式) vs Function Declaration (FD 函数声明): -* FE appear within context of a larger expression -* \ No newline at end of file +Multiple Function Expression e.g. +```js +// This function expression defines a function that squares its argument. +// Note that we assign it to a variable +const square = function(x) { return x*x; }; + +// Function expressions can include names, which is useful for recursion. +const f = function fact(x) { if (x <= 1) return 1; else return x*fact(x-1); }; + +// Function expressions can also be used as arguments to other functions: +[3,2,1].sort(function(a,b) { return a-b; }); + +// Function expressions are sometimes defined and immediately invoked: +let tensquared = (function(x) {return x*x;}(10)); +``` + +**Function Expression (FE 函数表达式)**: +* FE appear within context of a larger expression, or within statement +* name of function in FE is *optional*. (e.g. 1st FE e.g. has no function name) +* FE/FD declare variable: + * How FD use variable: (follow e.g. in 8.1.1 `function factorial(x)`) declares a variable and assigns a function obj to it. + * How FE use variable: developer can decide whether assign the newly defined function obj to a const or var, so we can refer to it mult-times later. (e.g. 3rd & 5th FE e.g. does not assign function obj to obj, and directly use it) +* Good practice: assign FE to `const` to protect function obj. + +FD vs (assign FE to variable after creation): +* Function defined by FD: the func obj are created before the script get executed (i.e. hoisted), so we can call these functions from code that appears above FD. +* Functions defined by FE **DO NOT EXIST** until FE are evaluated. +* To invoke a function (either defined using FE/FD), JS must can refer to it, function defined by FE cannot be referred until it's assigned to a variable