JavaScript: Functions Erick Kurniawan, S.Kom
JavaScript: Functions Outline •Introduction •Program Modules in JavaScript •Programmer-Defined Functions •Function Definitions •Random-Number Generation •Example: Game of Chance •Another Example: Random Image Generator •Scope Rules •JavaScript Global Functions •Recursion •Recursion vs. Iteration
Tujuan
Pada tutorial ini anda akan belajar: Bagaimana membangun program secara modular dari bagian kecil yang disebut functions.
Dapat membuat functions baru.
Untuk mengerti mekanisme yang digunakan untuk melewatkan information antar functions.
Untuk memperkenalkan teknik simulasi yang menggunakan random-number generation.
Untuk mengerti bagaimana visibility dari identifiers dibatasi pada area tertentu dari program.
Introduction
Design dari Software Memecah software menjadi modules Mudah untuk di-maintain dan debug
Divide and conquer
Program Modules dalam JavaScript
Modules dalam JavaScript Functions
Methods Milik object
JavaScript menyertakan banyak pre-defined methods Dikombinasikan dengan programmer-defined methods untuk membuat program
Program Modules dalam JavaScript
Functions Dimulai dengan pemanggilan function
Menerima informasi yang diperlukan melalui arguments (parameters)
Boss-Worker relationship Memanggil function Mengembalikan nilai ketika selesai Dapat mempunyai banyak tiers
Program Modules dalam JavaScript boss
worker1
worker4
worker2
worker5
worker3
Program Modules dalam JavaScript
Pemanggilan Function Name
Left parenthesis
Arguments dipisahkan dengan koma Constants, variables or expressions
Right parenthesis
Examples:
total += parseFloat( inputValue ); total += parseFloat( s1 + s2 );
Programmer-Defined Functions
Mendefinisikan functions Semua variables dideklarasikan dalam function disebut local Tidak dapat diakses dari luar function
Parameters Juga merupakan local variables
Mendukung reusability Program lebih pendek Nama fungsi jelas
Function Definitions
Format dari definisi function function function-name( parameter-list ) { declarations and statements }
Nama fungsi harus valid
Parameter merupakan variabel yang dapat menerima argumen Jumlah parameter harus sama dengan fungsi pemanggil Bisa kosong
Declarations dan statements Function body (“block” dari code)
Function Definitions
Returning control return statement
Dapat mengembalikan nilai atau tidak mengembalikan nilai
return expression; Tidak mengembalikan nilai sama dengan return;
Tidak mengembalikan nilai jika terjadi error
Function Definitions
Menulis function untuk mengkuadratkan dua angka for loop from 1 to 10
Pass each number as argument to square
return value of argument multiplied by itself
menampilkan hasil
1
2
3
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4 5
6
7 8 9 10
A Programmer-Defined square Function
11 12
<script type = "text/javascript">
13
31
32 33
34
Function Definitions
Mencari nilai maximum dari 3 angka Prompt for 3 inputs
Konversi ke tipe numbers
Pass to maximum
Math.max
1
2
3
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4 5
6
7 8 9 10
Finding the Maximum of Three Values
11 12
<script type = "text/javascript">
13
38
39 40
41
42 43
Click Refresh (or Reload) to run the script again
44
Random-Number Generation
Random-number generation introduces element of chance Math.random var randomValue = Math.random();
Floating point value between 0 and 1
Mengatur range by scaling and shifting
Math.floor Always round down
Math.floor( 1 + Math.random() * 6 )
1
2
3
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4 5
-->
7 8 9 10
Shifted and Scaled Random Integers
11 12
<script type = "text/javascript">
13
33
34 35
36
37 38
Click Refresh (or Reload) to run the script again
39
1
2
3
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4 5
6
7 8 9 10
Roll a Six-Sided Die 6000 Times
11 12
<script type = "text/javascript">
13
61
62 63
64
65 66
Click Refresh (or Reload) to run the script again
67
Example: Game of Chance
Craps Click Roll Dice
Text fields menunjukan rolls, sum dan point
Status bar menampilkan hasilnya
Example: Game of Chance
Menggunakan XHTML forms Mendapatkan multiple inputs
action attribute yang kosong
name attribute mengijinkan scripts untuk berinteraksi dengan form
Event handling dan event-driven programming function sebagai event
Onclick
Constants Variable yang tidak bisa di modifikasi
Ada di banyak bahasa, tidak di support JavaScript Pemberian nama dengan huruf besar semua
Membuat nilai lebih mudah untuk diubah / diingat
Example: Game of Chance
Mengganti properties Diakses dengan notasi dot (.)
value property dari text fields
status property dari window
1
2
3
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4 5
6
7 8 9 10
Program that Simulates the Game of Craps
11 12
<script type = "text/javascript">
13
87
88 89
90 91
111
A text XHTML GUI component
A button XHTML GUI component
Browser’s status bar
Another Example: Random Image Generator
Randomly selecting an image Images have integer names (i.e., 1.gif, 2.gif, …, 7.gif)
Generate random number in proper range
Update src property
1
2
3
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4 5
-->
7 8 9 10
Random Image Generator
11 12
<script type = "text/javascript">
13
18
19 20
21 22 23 24
Click Refresh (or Reload) to run the script again
25
Scope Rules
Scope Portion of program where identifier can be referenced
Inside function is local or function scope Identifiers exist only between opening and closing braces Local variables hide global variables
Scope Rules
Scope demonstration Global variable x initialized to 1
start has local variable x initialized to 5
functionA has local variable x initialized to 25
functionB has no local variable x
Observe output of each function
1
2
3
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4 5
-->
7 8 9 10
A Scoping Example
11 12
<script type = "text/javascript">
13
52
53 54
55
56
+ "" );
JavaScript Global Functions
Global object Always available
Provides 7 methods
Do not need to explicitly reference Global before method call
Global function escape
eval
isFinite
isNaN
Description This function takes a string argument and returns a string in which all spaces, punctuation, accent characters and any other character that is not in the ASCII character set (see Appendix D, ASCII Character Set) are encoded in a hexadecimal format (see Appendix E, Number Systems) that can be represented on all platforms. This function takes a string argument representing JavaScript code to execute. The JavaScript interpreter evaluates the code and executes it when the eval function is called. This function allows JavaScript code to be stored as strings and executed dynamically. This function takes a numeric argument and returns true if the value of the argument is not NaN, Number.POSITIVE_INFINITY or Number.NEGATIVE_INFINITY; otherwise, the function returns false. This function takes a numeric argument and returns true if the value of the argument is not a number; otherwise, it returns false. The function is commonly used with the return value of parseInt or parseFloat to determine whether the result is a proper numeric value.
Fig. 10.9 JavaScript global functions.
Global function parseFloat
parseInt
unescape
Description This function takes a string argument and attempts to convert the beginning of the string into a floatingpoint value. If the conversion is unsuccessful, the function returns NaN; otherwise, it returns the converted value (e.g., parseFloat( "abc123.45" ) returns NaN, and parseFloat( "123.45abc" ) returns the value 123.45). This function takes a string argument and attempts to convert the beginning of the string into an integer value. If the conversion is unsuccessful, the function returns NaN; otherwise, it returns the converted value (e.g., parseInt( "abc123" ) returns NaN, and parseInt( "123abc" ) returns the integer value 123). This function takes an optional second argument, from 2 to 36, specifying the radix (or base) of the number. Base 2 indicates that the first argument string is in binary format, base 8 indicates that the first argument string is in octal format and base 16 indicates that the first argument string is in hexadecimal format. See see Appendex E, Number Systems, for more information on binary, octal and hexadecimal numbers. This function takes a string as its argument and returns a string in which all characters previously encoded with escape are decoded.
Fig. 10.9 JavaScript global functions.
Recursion
Recursive functions Memanggil dirinya sendiri Recursion step atau recursive call Bagian dari return statement
Harus memiliki base case Menyederhanakan masalah Mengembalikan nilai dengan memanggil dirinya sendiri
Recursion
Factorials Product of calculation n · (n - 1) · (n - 2) · … · 1
Iterative approach:
var factorial = 1; for ( var counter = number; counter >= 1; -counter ) factorial *= counter;
Final value = 120 5!
5!
5 * 4! 4 * 3! 3 * 2! 2 * 1! 1 (a) Procession of recursive calls.
5! = 5 * 24 = 120 is returned 5 * 4! 4! = 4 * 6 = 24 is returned 4 * 3! 3! = 3 * 2 = 6 is returned 3 * 2! 2! = 2 * 1 = 2 is returned 2 * 1! 1 returned 1 (b) Values returned from each recursive call.
1
2
3
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4 5
6
7 8 9 10
Recursive Factorial Function
11 12
<script language = "javascript">
13
document.writeln( "
Factorials of 1 to 10
" );
14
document.writeln(
15
"
" );
16 17 18 19
for ( var i = 0; i <= 10; i++ ) document.writeln( "" + i + "! | " + factorial( i ) + " |
" );
20 21 22
document.writeln( "
" );
23
// Recursive definition of function factorial
24
function factorial( number )
25
{
26
if ( number <= 1 )
27
return 1;
28
else
29
return number * factorial( number - 1 );
30 31 32
// base case
}
33