functionshowMessage() {let message ="Hello, I'm JavaScript!"; // local variablealert( message );}showMessage(); // Hello, I'm JavaScript!alert( message ); // <-- Error! The variable is local to the function
Outer variables
let userName ='John';functionshowMessage() { userName ="Bob"; // (1) changed the outer variablelet message ='Hello, '+ userName;alert(message);}alert( userName ); // John before the function callshowMessage();alert( userName ); // Bob, the value was modified by the function
let userName ='John';functionshowMessage() {let userName ="Bob"; // declare a local variablelet message ='Hello, '+ userName; // Bobalert(message);}// the function will create and use its own userNameshowMessage();alert( userName ); // John, unchanged, the function did not access the outer variable
Parameters
functionshowMessage(from, text) { from ='*'+ from +'*'; // make "from" look niceralert( from +': '+ text );}let from ="Ann";showMessage(from,"Hello"); // *Ann*: Hello// the value of "from" is the same, the function modified a local copyalert( from ); // Ann
functionshowMessage(from, text ="no text given") {alert( from +": "+ text );}showMessage("Ann"); // Ann: no text givenfunctionshowMessage(from, text =anotherFunction()) {// anotherFunction() only executed if no text given// its result becomes the value of text}
Returning a value
return 可以使用在函式的任何位置,一旦返回值,函式停止執行。
functioncheckAge(age) {if (age >18) {returntrue; } else {returnconfirm('Do you have permission from your parents?'); }}let age =prompt('How old are you?',18);if ( checkAge(age) ) {alert( 'Access granted' );} else {alert( 'Access denied' );}
showMessage(..) // shows a messagegetAge(..) // returns the age (gets it somehow)calcSum(..) // calculates a sum and returns the resultcreateForm(..) // creates a form (and usually returns it)checkPermission(..) // checks a permission, returns true/false
Functions == Comments
函式要簡短只做一個功能,如果功能太複雜,要拆成幾個小函式再組合起來。
functionshowPrimes(n) { nextPrime:for (let i =2; i < n; i++) {for (let j =2; j < i; j++) {if (i % j ==0) continue nextPrime; }alert( i ); // a prime }}// easier test & debug like comment readablefunctionshowPrimes(n) {for (let i =2; i < n; i++) {if (!isPrime(i)) continue;alert(i); // a prime }}functionisPrime(n) {for (let i =2; i < n; i++) {if ( n % i ==0) returnfalse; }returntrue;}