# Function 實例

js> function max(num1, num2) {
>     return num1 > num2 ? num1 : num2;
> }
js> var maximum = max;
js> max(10, 20);
20
js> maximum(10, 20);
20
js>

js> var max = function(num1, num2) {
>     return num1 > num2 ? num1 : num2;
> };
js> var maximum = max;
js> max(1, 2);
2
js> maximum(1, 2);
2
js>

var number = 10;
var obj = { x : 10 };
var array = [1, 2, 3];
var func = function() {
// do something...
};

js> var max = new Function('num1', 'num2', 'return num1 > num2 ? num1 : num2');
js> max(5, 6);
6
js>

js> var printIt = function(element) {
>     print(element);
> };
js> [1, 2, 3].forEach(printIt);
1
2
3
js> var comparator = function(num1, num2) {
>     return num1 - num2;
> };
js> [5, 1, 7, 3, 2].sort(comparator);
1,2,3,5,7
js>

js> [1, 2, 3].forEach(function(element) {
>     print(element);
> });
1
2
3
js> [5, 1, 7, 3, 2].sort(function(num1, num2) {
>     return num1 - num2;
> });
1,2,3,5,7
js>

js> (function() {
>     print('anonymous function...');
> })();
anonymous function...
js>

js> var maximum = function max(num1, num2) {
>     return num1 > num2 ? num1 : num2;
> };
js> maximum(10, 20);
20
js> max(10, 20);
js: "<stdin>", line 6: uncaught JavaScript runtime exception: ReferenceError: "max" is not defined.
at <stdin>:6

js>

js> var gcd = function g(num1, num2) {
>     return num2 != 0 ? g(num2, num1 % num2) : num1;
> };
js> gcd(10, 5);
5
js>

js> var gcd = function(num1, num2) {
>     return num2 != 0 ? arguments.callee(num2, num1 % num2) : num1;
> };
js> gcd(20, 10);
10
js>

js> var gcd = function g(num1, num2) {
>     return num2 != 0 ? g(num2, num1 % num2) : num1;
> };
js> gcd.length;
2
js>

• f.js
``func();function func() {    print('func');} ``

your_workspace> java org.mozilla.javascript.tools.shell.Main f.js
func

• f.js
``func();var func = function() {    print('func');};``

your_workspace> java org.mozilla.javascript.tools.shell.Main f.js
js: uncaught JavaScript runtime exception: TypeError: func is not a function, it is undefined.

var max = new Function('num1', 'num2', 'return num1 > num2 ? num1 : num2');