Javascript 5 : Function Part 3 ( Dengan 2 Parameter)

1:10 PG 0 Comments A+ a-

 

Function juga dapat dijalankan dengan lebih dari 1 parameter. Lihat contoh dibawah

// Write your function starting on line 3
var areaBox= function(length,width) {
return length * width
};

areaBox(6,2);

Function untuk perimeter of a rectangle memerlukan dua parameter dan formulanya adalah : length + length + width + width. Contoh untuk function pengiraan rectangle parameter adalah seperti:

var perimeterBox= function(length,width) {
return length + length + width + width
};

perimeterBox(6,2);
 
SCOPE

Scope mungkin global atau local. Variable yang di definasikan di luar function, boleh diakses dimana-mana once diorang di declare. Mereka dipanggil  global variables and their scope is global.

For example

var globalVar = "hello";

var foo = function() {
console.log(globalVar); // prints "hello"
}




hello

Variable globalVar boleh diakses di mana-mana termasuk didalam function foo.


Manakala variable yang dideclare didalam function dikenali sebagai local variables. Mereka tidak boleh diakses di luar dari function tersebut.


For example

var bar = function() {
var localVar = "howdy";
}

console.log(localVar); // error




// error

Error terjadi kerana kita cuba print localVar di luar function.


Dibawah adalah perbezaan yang jelas penggunaan scope global dan local.

var my_number = 7; //this has global scope

var timesTwo = function(number) {
my_number = number * 2;
console.log("Inside the function my_number is: ");
console.log(my_number);
};

timesTwo(7);

console.log("Outside the function my_number is: ")
console.log(my_number);


 





Inside the function my_number is: 
14
Outside the function my_number is:
14
CONTOH LOCAL (tambar perkataan var didalam function)
var my_number = 7; //this has global scope

var timesTwo = function(number) {
var my_number = number * 2;
console.log("Inside the function my_number is: ");
console.log(my_number);
};

timesTwo(7);

console.log("Outside the function my_number is: ")
console.log(my_number);




Inside the function my_number is: 
14
Outside the function my_number is:
7