JavaScript: The Good Parts 学习随笔(五)

4.4 参数

当函数被调用时,会得到一个参数列表,即arguments数组(并不是真的数组,只有length属性,不含方法)。

// Make a function that adds a lot of stuff.
// Note that defining the variable sum inside of
// the function does not interfere with the sum
// defined outside of the function. The function
// only sees the inner one.

var sum = function (  ) {
    var i, sum = 0;
    for (i = 0; i < arguments.length; i += 1) {
        sum += arguments[i];
    }
    return sum;
};

document.writeln(sum(4, 8, 15, 16, 23, 42)); // 108

4.5 返回

一个函数总会返回一个值,没有指定就是undefined。

如果函数调用时在前面加上一盒new,且返回的不是一个对象,则返回this,即该新对象。

4.6 异常

var add = function (a, b) {
    if (typeof a !== 'number' || typeof b !== 'number') {
        throw {
            name: 'TypeError',
            message: 'add needs numbers'
        }
    }
    return a + b;
}
// Make a try_it function that calls the new add
// function incorrectly.

var try_it = function (  ) {
    try {
        add("seven");
    } catch (e) {
        document.writeln(e.name + ': ' + e.message);
    }
}

tryIt(  );

 

 

posted @ 2013-01-16 20:20  dearRose  阅读(126)  评论(0编辑  收藏  举报