aboutsummaryrefslogtreecommitdiff
path: root/files/zh-tw/web/javascript/guide/functions/index.html
blob: af19983b6ff1032364fda9fdc7a5514fcda612dc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
---
title: 函式
slug: Web/JavaScript/Guide/Functions
translation_of: Web/JavaScript/Guide/Functions
---
<p>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Loops_and_iteration", "Web/JavaScript/Guide/Expressions_and_Operators")}}</p>

<p>函式是構成javascript的基本要素之一。一個函式本身就是一段JavaScript程序—包含用於執行某一個任務或計算的語法。要呼叫某一個函式之前,你必需先在這個函式欲執行的scope中定義它。</p>

<h2 id="定義函式">定義函式</h2>

<p>一個函式的定義由一系列的函式關鍵詞組成, 依次為:</p>

<ul>
 <li>函式的名稱。</li>
 <li>包圍在括號()中,並由逗號區隔的一個函式參數列表。</li>
 <li>包圍在大括號{}中,用於定義函式功能的一些JavaScript語句。</li>
</ul>

<p> </p>

<p>例如,以下的程式碼定義了一個名為square的簡單函式:</p>

<div>
<pre class="brush: js">function square(number) {
  return number * number;
}
</pre>
</div>

<p>函式square有一個參數,叫作number。這個函式只有一行程式碼,它會回傳number自乘的結果。函式的 <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/return" title="return"><code>return</code></a> 語法描述函式的返回值。</p>

<pre class="brush: js">return number * number;
</pre>

<p>原始參數(例如一個數字)被作為值傳遞給函式,如果呼叫的函式改變了這個參數的值,不會影響到函式外部的原始變數。</p>

<p>如果傳遞一個物件(例如 <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array" title="Array"><code>Array</code></a> 或自定義的其它物件)作為參數,而函式改變了這個物件的屬性,這樣的改變對函式外部是有作用的(因為是傳遞物件的位址),如下面的例子所示:</p>

<pre class="brush: js">function myFunc(theObject) {
  theObject.make = "Toyota";
}

var mycar = {make: "Honda", model: "Accord", year: 1998},
    x,
    y;

x = mycar.make;     // x 的值為 "Honda"

myFunc(mycar);
y = mycar.make;     // y 的值為 "Toyota"
                    // (屬性 make 被 function 改變)
</pre>

<p>請注意,重新給參數指定一個對象(物件),並不會對函式的外部有任何影響,因為這樣只是改變了參數的值,而不是改變了對象的一個屬性值:</p>

<pre class="brush: js">function myFunc(theObject) {
  theObject = {make: "Ford", model: "Focus", year: 2006};
}

var mycar = {make: "Honda", model: "Accord", year: 1998},
    x,
    y;

x = mycar.make;     // x 的值為 "Honda"

myFunc(mycar);
y = mycar.make;     // y 的值還是 "Honda" </pre>

<p>儘管上述函式定義都是用的是陳述式,函式也同樣可以由函式表達式來定義。這樣的函式可以是匿名的;它不必有名稱。例如,上面提到的函式square也可這樣來定義:</p>

<pre class="brush: js">var square = function(number) {return number * number};
var x = square(4) //x 的值為 16</pre>

<div>必要時,函式名稱可與函式表達式同時存在,並且可以用於在函式內部代指其本身(遞迴):</div>

<pre class="brush: js">var factorial = function fac(n) {return n&lt;2 ? 1 : n*fac(n-1)};

console.log(factorial(3));
</pre>

<p>函式表達式在將函式作為一個參數傳遞給其它函式時十分方便。下面的例子展示了一個叫map的函式如何​​被定義,而後呼叫一個匿名函式作為其第一個參數:</p>

<pre class="brush: js">function map(f,a) {
  var result = [], // Create a new Array
      i;
  for (i = 0; i != a.length; i++)
    result[i] = f(a[i]);
  return result;
}
</pre>

<p>下面的程式碼呼叫map函式並將一個匿名函式傳入作為第一個參數:</p>

<pre class="brush: js">map(function(x) {return x * x * x}, [0, 1, 2, 5, 10]);
// 結果會回傳 [0, 1, 8, 125, 1000]
</pre>

<p>除了上述的定義方式以外,我們也可以透過 <a href="/en-US/docs/JavaScript/Guide/Predefined_Core_Objects#Function_Object" title="en-US/docs/JavaScript/Guide/Predefined Core Objects#Function Object"><code>Function</code> constructor</a> 來定義, 類似 <a href="/en-US/docs/JavaScript/Guide/Functions#eval_Function" title="en-US/docs/JavaScript/Guide/Functions#eval_Function"><code>eval()</code></a>.</p>

<h2 id="呼叫函式">呼叫函式</h2>

<p>定義一個函式並不會自動的執行它。定義了函式僅僅是賦予函式以名稱並明確函式被呼叫時該做些什麼。呼叫函式才會以給定的參數真正執行這些動作。例如,一旦你定義了函式square,你可以如下這樣呼叫它:</p>

<pre class="brush: js">square(5);
</pre>

<p>上述程式碼把5傳遞給square函式。函式執行完會回傳25。</p>

<p>函式必須在呼叫區塊的可視範圍內,但函數也可以宣告在使用處的下面,如下列範例:</p>

<pre>console.log(square(5));
/* ... */
function square(n){return n*n}
</pre>

<p>The scope of a function is the function in which it is declared, or the entire program if it is declared at the top level. Note that this works only when defining the function using the above syntax (i.e. <code>function funcName(){}</code>). The code below will not work.</p>

<pre class="brush: js">console.log(square(5));
square = function (n) {
  return n * n;
}
</pre>

<p>The arguments of a function are not limited to strings and numbers. You can pass whole objects to a function, too. The <code>show_props</code> function (defined in <a href="/en-US/docs/JavaScript/Guide/Working_with_Objects#Objects_and_Properties" title="https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects#Objects_and_Properties">Working with Objects</a>) is an example of a function that takes an object as an argument.</p>

<p>A function can be recursive; that is, it can call itself. For example, here is a function that computes factorials recursively:</p>

<pre class="brush: js">function factorial(n){
  if ((n == 0) || (n == 1))
    return 1;
  else
    return (n * factorial(n - 1));
}
</pre>

<p>You could then compute the factorials of one through five as follows:</p>

<pre class="brush: js">var a, b, c, d, e;
a = factorial(1); // a gets the value 1
b = factorial(2); // b gets the value 2
c = factorial(3); // c gets the value 6
d = factorial(4); // d gets the value 24
e = factorial(5); // e gets the value 120
</pre>

<p>There are other ways to call functions. There are often cases where a function needs to be called dynamically, or the number of arguments to a function vary, or in which the context of the function call needs to be set to a specific object determined at runtime. It turns out that functions are, themselves, objects, and these objects in turn have methods (see the <a href="/en-US/docs/JavaScript/Guide/Obsolete_Pages/Predefined_Core_Objects/Function_Object" title="Function Object"><code>Function</code> object</a>). One of these, the <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function/apply" title="apply"><code>apply()</code></a> method, can be used to achieve this goal.</p>

<h2 id="Function_scope">Function scope</h2>

<p>Variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function. However, a function can access all variables and functions defined inside the scope in which it is defined. In other words, a function defined in the global scope can access all variables defined in the global scope. A function defined inside another function can also access all variables defined in it's parent function and any other variable to which the parent function has access.</p>

<pre class="brush: js">// The following variables are defined in the global scope
var num1 = 20,
    num2 = 3,
    name = "Chamahk";

// This function is defined in the global scope
function multiply() {
  return num1 * num2;
}

multiply(); // Returns 60

// A nested function example
function getScore () {
  var num1 = 2,
      num2 = 3;

  function add() {
    return name + " scored " + (num1 + num2);
  }

  return add();
}

getScore(); // Returns "Chamahk scored 5"
</pre>

<h2 id="閉包">閉包</h2>

<p>閉包是 JavaScript 最強大的特性之一。JavaScript 允許巢狀函式(nesting of functions)並給予內部函式完全訪問(full access)所有變數、與外部函式定義的函式(還有所有外部函式內的變數與函式)不過,外部函式並不能訪問內部函式的變數與函式。這保障了內部函式的變數安全。另外,由於內部函式能訪問外部函式定義的變數與函式,將存活得比外部函式還久。A closure is created when the inner function is somehow made available to any scope outside the outer function.</p>

<pre class="brush: js">var pet = function(name) {          // The outer function defines a variable called "name"
      var getName = function() {
        return name;                // The inner function has access to the "name" variable of the outer function
      }

      return getName;               // Return the inner function, thereby exposing it to outer scopes
    },
    myPet = pet("Vivie");

myPet();                            // Returns "Vivie"
</pre>

<p>It can be much more complex than the code above. An object containing methods for manipulating the inner variables of the outer function can be returned.</p>

<pre class="brush: js">var createPet = function(name) {
  var sex;

  return {
    setName: function(newName) {
      name = newName;
    },

    getName: function() {
      return name;
    },

    getSex: function() {
      return sex;
    },

    setSex: function(newSex) {
      if(typeof newSex == "string" &amp;&amp; (newSex.toLowerCase() == "male" || newSex.toLowerCase() == "female")) {
        sex = newSex;
      }
    }
  }
}

var pet = createPet("Vivie");
pet.getName();                  // Vivie

pet.setName("Oliver");
pet.setSex("male");
pet.getSex();                   // male
pet.getName();                  // Oliver
</pre>

<p>In the codes above, the <code>name</code> variable of the outer function is accessible to the inner functions, and there is no other way to access the inner variables except through the inner functions. The inner variables of the inner function act as safe stores for the inner functions. They hold "persistent", yet secure, data for the inner functions to work with. The functions do not even have to be assigned to a variable, or have a name.</p>

<pre class="brush: js">var getCode = (function(){
  var secureCode = "0]Eal(eh&amp;2";    // A code we do not want outsiders to be able to modify...

  return function () {
    return secureCode;
  };
})();

getCode();    // Returns the secret code
</pre>

<p>There are, however, a number of pitfalls to watch out for when using closures. If an enclosed function defines a variable with the same name as the name of a variable in the outer scope, there is no way to refer to the variable in the outer scope again.</p>

<pre class="brush: js">var createPet = function(name) {  // Outer function defines a variable called "name"
  return {
    setName: function(name) {    // Enclosed function also defines a variable called "name"
      name = name;               // ??? How do we access the "name" defined by the outer function ???
    }
  }
}
</pre>

<p>The magical <code>this</code> variable is very tricky in closures. They have to be used carefully, as what <code>this</code> refers to depends completely on where the function was called, rather than where it was defined. An excellent and elaborate article on closures can be found <a class="external" href="http://jibbering.com/faq/notes/closures/">here</a>.</p>

<h2 id="Using_the_arguments_object">Using the arguments object</h2>

<p>The arguments of a function are maintained in an array-like object. Within a function, you can address the arguments passed to it as follows:</p>

<pre class="brush: js">arguments[i]
</pre>

<p>where <code>i</code> is the ordinal number of the argument, starting at zero. So, the first argument passed to a function would be <code>arguments[0]</code>. The total number of arguments is indicated by <code>arguments.length</code>.</p>

<p>Using the <code>arguments</code> object, you can call a function with more arguments than it is formally declared to accept. This is often useful if you don't know in advance how many arguments will be passed to the function. You can use <code>arguments.length</code> to determine the number of arguments actually passed to the function, and then access each argument using the <code>arguments</code> object.</p>

<p>For example, consider a function that concatenates several strings. The only formal argument for the function is a string that specifies the characters that separate the items to concatenate. The function is defined as follows:</p>

<pre class="brush: js">function myConcat(separator) {
   var result = "", // initialize list
       i;
   // iterate through arguments
   for (i = 1; i &lt; arguments.length; i++) {
      result += arguments[i] + separator;
   }
   return result;
}
</pre>

<p>You can pass any number of arguments to this function, and it concatenates each argument into a string "list":</p>

<pre class="brush: js">// returns "red, orange, blue, "
myConcat(", ", "red", "orange", "blue");

// returns "elephant; giraffe; lion; cheetah; "
myConcat("; ", "elephant", "giraffe", "lion", "cheetah");

// returns "sage. basil. oregano. pepper. parsley. "
myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley");
</pre>

<p>Please note that the <code>arguments</code> variable is "array-like", but not an array. It is array-like in that is has a numbered index and a <code>length</code> property. However, it does not possess all of the array-manipulation methods.</p>

<p>See the <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function" title="en-US/docs/JavaScript/Reference/Global Objects/Function"><code>Function</code> object</a> in the JavaScript Reference for more information.</p>

<h2 id="Predefined_functions">Predefined functions</h2>

<p>JavaScript has several top-level predefined functions:</p>

<ul>
 <li>{{ web.link("#eval_function", "eval") }}</li>
 <li>{{ web.link("#isFinite_function", "isFinite") }}</li>
 <li>{{ web.link("#isNaN_function", "isNaN") }}</li>
 <li>{{ web.link("#parseInt_and_parseFloat_functions", "parseInt and parseFloat") }}</li>
 <li>{{ web.link("#Number_and_String_functions", "Number and String") }}</li>
 <li>{{ web.link("#escape_and_unescape_functions", "encodeURI, decodeURI, encodeURIComponent, and decodeURIComponent") }} (all available with Javascript 1.5 and later).</li>
</ul>

<p>The following sections introduce these functions. See the <a href="/en-US/docs/JavaScript/Reference" title="en-US/docs/JavaScript/Reference">JavaScript Reference</a> for detailed information on all of these functions.</p>

<h3 id="eval_Function">eval Function</h3>

<p>The <code>eval</code> function evaluates a string of JavaScript code without reference to a particular object. The syntax of <code>eval</code> is:</p>

<pre class="brush: js">eval(expr);
</pre>

<p>where <code>expr</code> is a string to be evaluated.</p>

<p>If the string represents an expression, <code>eval</code> evaluates the expression. If the argument represents one or more JavaScript statements, eval performs the statements. The scope of <code>eval</code> code is identical to the scope of the calling code. Do not call <code>eval</code> to evaluate an arithmetic expression; JavaScript evaluates arithmetic expressions automatically.</p>

<h3 id="isFinite_function">isFinite function</h3>

<p>The <code>isFinite</code> function evaluates an argument to determine whether it is a finite number. The syntax of <code>isFinite</code> is:</p>

<pre class="brush: js">isFinite(number);
</pre>

<p>where <code>number</code> is the number to evaluate.</p>

<p>If the argument is <code>NaN</code>, positive infinity or negative infinity, this method returns <code>false</code>, otherwise it returns <code>true</code>.</p>

<p>The following code checks client input to determine whether it is a finite number.</p>

<pre class="brush: js">if(isFinite(ClientInput)){
   /* take specific steps */
}
</pre>

<h3 id="isNaN_function">isNaN function</h3>

<p>The <code>isNaN</code> function evaluates an argument to determine if it is "NaN" (not a number). The syntax of <code>isNaN</code> is:</p>

<pre class="brush: js">isNaN(testValue);
</pre>

<p>where <code>testValue</code> is the value you want to evaluate.</p>

<p>The <code>parseFloat</code> and <code>parseInt</code> functions return "NaN" when they evaluate a value that is not a number. <code>isNaN</code> returns true if passed "NaN," and false otherwise.</p>

<p>The following code evaluates <code>floatValue</code> to determine if it is a number and then calls a procedure accordingly:</p>

<pre class="brush: js">var floatValue = parseFloat(toFloat);

if (isNaN(floatValue)) {
   notFloat();
} else {
   isFloat();
}
</pre>

<h3 id="parseInt_and_parseFloat_functions">parseInt and parseFloat functions</h3>

<p>The two "parse" functions, <code>parseInt</code> and <code>parseFloat</code>, return a numeric value when given a string as an argument.</p>

<p>The syntax of <code>parseFloat</code> is:</p>

<pre class="brush: js">parseFloat(str);
</pre>

<p>where <code>parseFloat</code> parses its argument, the string <code>str</code>, and attempts to return a floating-point number. If it encounters a character other than a sign (+ or -), a numeral (0-9), a decimal point, or an exponent, then it returns the value up to that point and ignores that character and all succeeding characters. If the first character cannot be converted to a number, it returns "NaN" (not a number).</p>

<p>The syntax of <code>parseInt</code> is:</p>

<pre class="brush: js">parseInt(str [, radix]);
</pre>

<p><code>parseInt</code> parses its first argument, the string <code>str</code>, and attempts to return an integer of the specified <code>radix</code> (base), indicated by the second, optional argument, <code>radix</code>. For example, a radix of ten indicates to convert to a decimal number, eight octal, sixteen hexadecimal, and so on. For radixes above ten, the letters of the alphabet indicate numerals greater than nine. For example, for hexadecimal numbers (base 16), A through F are used.</p>

<p>If <code>parseInt</code> encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. If the first character cannot be converted to a number in the specified radix, it returns "NaN." The <code>parseInt</code> function truncates the string to integer values.</p>

<h3 id="Number_and_String_functions">Number and String functions</h3>

<p>The <code>Number</code> and <code>String</code> functions let you convert an object to a number or a string. The syntax of these functions is:</p>

<pre class="brush: js">var objRef;
objRef = Number(objRef);
objRef = String(objRef);
</pre>

<p><code>objRef 是物件的參照</code>。 Number uses the valueOf() method of the object; String uses the toString() method of the object.</p>

<p>下列範例將<code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/Date" title="en-US/docs/JavaScript/Reference/Global Objects/Date"> 日期</a></code> 物件轉換為可讀字串。</p>

<pre class="brush: js">var D = new Date(430054663215),
    x;
x = String(D); // x 等於 "星期二 八月 18 04:37:43 GMT-0700  1983"
</pre>

<p>下列範例將 <code><a class="internal" href="/en-US/docs/JavaScript/Reference/Global_Objects/String" title="en-US/docs/JavaScript/Reference/Global Objects/String">字串</a></code> 物件轉換為 <code><a class="internal" href="/en-US/docs/JavaScript/Reference/Global_Objects/Number" title="en-US/docs/JavaScript/Reference/Global Objects/Number">數字</a></code> 物件。</p>

<pre class="brush: js">var str = "12",
    num;
num = Number(字串);
</pre>

<p>使用 DOM 方法 <code>write()</code> 與 JavaScript <code>typeof</code> 運算子.</p>

<pre class="brush: js">var str = "12",
    num;
document.write(typeof str);
document.write("&lt;br/&gt;");
num = Number(str);
document.write(typeof num);
</pre>

<h3 id="escape_與_unescape_函式(JavaScript_1.5後去除)">escape 與 unescape 函式(JavaScript 1.5後去除)</h3>

<p><code>escape</code><code>unescape</code> 對於非ASCII 字元無法處理。 在 JavaScript 1.5 之後改用 <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/encodeURI" title="en-US/docs/JavaScript/Reference/Global_Functions/encodeURI">encodeURI</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/decodeURI" title="en-US/docs/JavaScript/Reference/Global_Functions/decodeURI">decodeURI</a></code>, <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent" title="en-US/docs/JavaScript/Reference/Global_Functions/encodeURIComponent">encodeURIComponent</a></code>, 與 <code><a href="/en-US/docs/JavaScript/Reference/Global_Objects/decodeURIComponent" title="en-US/docs/JavaScript/Reference/Global_Functions/decodeURIComponent">decodeURIComponent</a></code>.</p>

<p><code>escape</code><code>unescape</code> 用於編碼與解碼字串。 <code>escape</code> 函式回傳十六進位編碼。 <code>unescape</code> 函式會將十六進位的編碼轉換回 ASCII 字串。</p>

<p>這些函式的語法是:</p>

<pre class="brush: js">escape(字串);
unescape(字串);
</pre>

<p>這些函式常被用於伺服器後端中處理姓名等資料。</p>