知識社群登入
位置: Web Programming > 文件區 > Javascript > Function
by 蘇德宙, 2010-04-07 15:56, 人氣(1419)
定義與呼叫
function print(x, y, z)
{
    if (!z) z = 3; // 未傳遞的參數 z 會設成 undefined,使用預設值的小技巧, or z = z || 3;
    alert(x + " " + y); 
    // 如果沒有 return,則傳回 undefined
    // variable: call by value, object: call by reference
}
print("hello", "world");


函式 expression and declaration
var f = function() { ... }  // expression
function() { ... }  // declaration,不可以設定給變數 or 當成參數
 
 
巢狀函式
function a(x)
{
    function b(x) { return x; }  // 定義在函式裏,僅限於函式內使用
    return x * b(x);
}
 
 
函式 literal (沒有名子,anonymous function)
var f = function(x) { return x; } // 函式的參考值存在變數 f 中
var f = function fact(x) { if (x<=1) return 1; else return x * fact(x-1); } // fact 只用於函式內部參考
 
 
不定參數 (arguments 物件)
function max(/* ... */)
{
    var m = Number.NEGATIVE_INFINITY;
    for (var i=0; i<arguments.length; i++)
        if (arguments[i] > m) m = arguments[i];
    return m;
}
 
// deprecated, arguments.callee 代表目前執行的函式,ex 沒有函數名稱的遞回
function(x)
{
    if (x<=1) return 1; else return x * arguments.callee(x-1);
}
 
 
物件當參數 (name/value 關係,比較不會亂,也可以傳指定的參數)
function arycpy(args)
{
    arraycopy(args.from, args.from_start || 0, // 預設值
              args.to, args.to_start || 0,
              args.len);
}
var a = [1, 2, 3, 4];
var b = new Array(4);
arycpy({from:a , to:b, len:4});
 
 
函式當參數
function f2(f, a, b) { return f(a, b); }
f2(function(x,y) { return x-y; }, a, b);
 
 
檢查參數的型別 (typeof, instanceof)
funciton f(x)
{
    if (!x) // undefined, null
    typeof v == "number,boolean,string,function,object,undefined"),如果是 array, null 會是 object
    x instanceof Array // 針對 object
    
    function test() {};
    var a = new test();
    console.log(a instanceof test);  // true
    console.log(typeof test=="function");  // true
    console.log(typeof a=="object");  // true
    console.log(typeof a=="function");  // false
}
 
 
定義並同時呼叫
var val = (function(x) { return x * x; })(10);
by 蘇德宙, 2011-02-07 12:40, 人氣(1275)
隱含的環境參數 this
// method ,代表此 method 的物件
var rect  = {
        width: 10, height: 10,
        setSize: function(w, h) {
            this.width = w, this.height = h;
        }
}
rect.setSize(20, 20);
 
// 一般 function,全域物件
var a = 0;
function f()
{
    var a = 1;
    alert (this.a);  // 0
    alert(a);  // 1
}
 
//
<div id=foo>click me!</div>
<script>
  function obj(el) {
    this.id = 1;
    this.el = el;
    this.el.onclick = this.clickHandler;
  }  
  obj.prototype.handler = function(event) {
    alert(this.id);
  }
 
  var a = new obj(document.getElementById("foo"));
  a.handler();          // 隱性地傳入 a 物件當做 handler 中的 this

  a.handler.call(a.el); // call 的第一個參數傳入 a.el 當做 handler 中的 this
  // click div 時,browser 會將 dom 元素傳入當做 handler 中的 this
</script>