TIL coding
  • Initial page
  • 排版
  • Flexbox
  • Grid
  • jQuery
  • Untitled
  • JavaScript
    • An Introduction to JavaScript
    • Hello, world!
    • Code structure
    • The modern mode, "use strict"
    • Variables
    • Data types
    • Type Conversions
    • Operators
    • Comparisons
    • Interaction: alert, prompt, confirm
    • Conditional operators: if, '?'
    • Logical operators
    • Loops: while and for
    • The "switch" statement
    • Functions
    • Function expressions and arrows
    • JavaScript specials
    • Comments
    • Ninja code
    • Automated testing with mocha
    • Polyfills
    • Objects
    • Garbage collection
    • Symbol type
    • Object methods, "this"
    • Object to primitive conversion
    • Constructor, operator "new"
    • Methods of primitives
    • Numbers
    • Strings
    • Arrays
    • Array methods
    • Iterables
    • Map, Set, WeakMap and WeakSet
    • Object.keys, values, entries
    • Destructuring assignment
    • Date and time
    • JSON methods, toJSON
    • Recursion and stack
    • Rest parameters and spread operator
    • Closure
    • The old "var"
    • Global object
    • Function object, NFE
    • The "new Function" syntax
    • Scheduling: setTimeout and setInterval
    • Decorators and forwarding, call/apply
    • Function binding
    • Currying and partials
    • Arrow functions revisited
    • Property flags and descriptors
    • Property getters and setters
    • Prototypal inheritance
    • F.prototype
    • Native prototypes
    • Prototype methods, objects without __proto__
    • The “class” syntax
    • Class inheritance
    • Static properties and methods
    • Private and protected properties and methods
    • Extending built-in classes
    • Class checking: "instanceof"
    • Mixins
    • Error handling, "try..catch"
    • Custom errors, extending Error
    • Introduction: callbacks
    • Promise
    • Promises chaining
    • Error handling with promises
    • Promise API
  • Bootstrap
    • Navbar
Powered by GitBook
On this page
  • Callback functions
  • Function Expression vs Function Declaration
  • Arrow functions

Was this helpful?

  1. JavaScript

Function expressions and arrows

函式後面加 () 代表執行程式,沒有 () 代表原始碼。

// function declaration
function sayHi() {
  alert( "Hello" );
}

// function expression
let sayHi = function() {
  alert( "Hello" );
};

function sayHi() {   // (1) create
  alert( "Hello" );
}

let func = sayHi;    // (2) copy

func(); // Hello     // (3) run the copy (it works)!
sayHi(); // Hello    //     this still works too (why wouldn't it)

func f {...}、for {...}、if {....} 都不需要;結尾,但 let f = ... ; 代表一個值需要用;結尾。

function sayHi() {
  // ...
}

let sayHi = function() {
  // ...
};

Callback functions

帶入函式,預期之後如果需要可以被執行。

function ask(question, yes, no) {
  if (confirm(question)) yes()
  else no();
}

function showOk() {
  alert( "You agreed." );
}

function showCancel() {
  alert( "You canceled the execution." );
}

// usage: callback functions showOk, showCancel are passed as arguments to ask
ask("Do you agree?", showOk, showCancel);

// same
function ask(question, yes, no) {
  if (confirm(question)) yes()
  else no();
}

// anonymous callback functions
ask(
  "Do you agree?",
  function() { alert("You agreed."); },
  function() { alert("You canceled the execution."); }
);

Function Expression vs Function Declaration

當執行到的時候,Function Expression 被創造出來, Function Declaration 可以在全域使用。

// Function Declaration
function sum(a, b) {
  return a + b;
}

// Function Expression
let sum = function(a, b) {
  return a + b;
};

// example
sayHi("John"); // Hello, John

function sayHi(name) {
  alert( `Hello, ${name}` );
}

sayHi("John"); // error!

let sayHi = function(name) {  // (*) no magic any more
  alert( `Hello, ${name}` );
};

若函式被宣告在 code blocks 無法作為全域使用。

let age = 16; // take 16 as an example

if (age < 18) {
  welcome();               // \   (runs)
                           //  |
  function welcome() {     //  |
    alert("Hello!");       //  |  Function Declaration is available
  }                        //  |  everywhere in the block where it's declared
                           //  |
  welcome();               // /   (runs)
} else {
  function welcome() {     //  for age = 16, this "welcome" is never created
    alert("Greetings!");
  }
}

// Here we're out of curly braces,
// so we can not see Function Declarations made inside of them.
welcome(); // Error: welcome is not defined

// global function
let age = prompt("What is your age?", 18);
let welcome;

if (age < 18) {
  welcome = function() {
    alert("Hello!");
  };
} else {
  welcome = function() {
    alert("Greetings!");
  };
}

welcome(); // ok now

// same shorter
let age = prompt("What is your age?", 18);

let welcome = (age < 18) ?
  function() { alert("Hello!"); } :
  function() { alert("Greetings!"); };

welcome(); // ok now

Arrow functions

expression 不用加 return。

let func = (arg1, arg2, ...argN) => expression

// same
let func = function(arg1, arg2, ...argN) {
  return expression;
};

//example
let sum = (a, b) => a + b;

alert( sum(1, 2) ); // 3

/* The arrow function is a shorter form of:
let sum = function(a, b) {
  return a + b;
};
*/


let double = n => n * 2;

alert( double(3) ); // 6
// same as
// let double = function(n) { return n * 2 }

// no arguments parentheses should be present
let sayHi = () => alert("Hello!");

sayHi();

多行 arrow functions,需要加 return。

let sum = (a, b) => {  // the curly brace opens a multiline function
  let result = a + b;
  return result; // if we use curly braces, use return to get results
};

alert( sum(1, 2) ); // 3
PreviousFunctionsNextJavaScript specials

Last updated 5 years ago

Was this helpful?