[教學]Javascript: 函式的應用

提供WOG各方面的技術問題,並提供最新path更新。

版主: 涅魂, 簫哥, 10度C~


涅魂
 
文章: 4463
註冊時間: 2004-01-04 11:17 am
來自: Taiwan
性別: 男生

[教學]Javascript: 函式的應用

文章涅魂 » 2009-09-17 5:07 am

以下針對函式的arguments, apply, call, callee, caller做簡單的介紹

arguments:
arguments是函式所提供的一組區域變數,就如同this。arguments所指向的是當前函式的所有參數,能用如同陣列般的方式來存取。

例子:
代碼: 選擇全部
function test() {
  alert([b][u]arguments[/u][/b][2]);
}
test(1, 2, 3); // show 3
test('a', 'b', 'd');  // show d


apply/call:
apply和call都是function的method。

call能夠對函式進行調用,並能將call的第一個參數設置為被調用的函式的this變數,其餘變數則當做被調用函式的參數依序帶入。

apply用法如同call,但第二參數必須是陣列,而這陣列將成為被調用函式的參數陣列

例子:
代碼: 選擇全部
function add(a, b) {
  alert( a == b ?1:2);
}

add(1, 2);
add.[b][u]call[/u][/b](null, 1, 2);
add.[b][u]apply[/u][/b](null, [1, 2]);


caller:
caller是arguments的property,代表呼叫當前函式的來源者

例子:
代碼: 選擇全部
function test1() {
  test2();
}
function test2() {
  alert(arguments.[b][u]caller[/u][/b]); //show test1(){test2();}
}
test1();



callee:
callee是arguments的property,代表當前執行中的函式,通常會使用這個property讓匿名函式執行遞迴呼叫

例子:
代碼: 選擇全部
function myalert(msg) {
  if(arguments.length == 1) {
    alert(msg);
  } else {
    for(var i =0, len = arguments.length; i < len; i++) {arguments.callee(arguments[i]);}
  }
}

myalert('test0', 'test1', 'test2');  //show "test0",  "test1", "test2" one by one


以上,有任何問題或建議請留言指教。 :D


圖檔

回到 Online FF Battle-WOG官方聯盟推廣處

誰在線上

正在瀏覽這個版面的使用者:沒有註冊會員 和 16 位訪客