Javascript函数

1. 函数定义

var f = function fact(x) { if (x <= 1) return 1; else return x*fact(x-1); };
这样外部可以调用f(5)  但是不能调用fact(5);

去掉var f = 则可以直接在外部调用fact(5);

This line of codedefines an unnamed function and stores a reference to it in the variable f. It does not actually create a function named fact( ), but it does allow the body of the function to refer to itself using that name. Note, however, that this type of named function literal is not properly implemented before JavaScript 1.5.

2. 像变量一样使用函数

var a =square(4);  // a contains the number 16

var b = square;     // Now b refers to the same function thatsquare does

var c = b(5);       // c contains the number 25

3. 函数参数 callee

In addition to itsarray elements, the Arguments object defines a callee property that refers tothe function that is currently being executed. This is useful, for example, toallow unnamed functions to invoke themselves recursively. For instance, here isan unnamed function literal that computes factorials:

function(x) {

    if (x <= 1) return 1;

    return x * arguments.callee(x-1);

}

Throughout this section we've been referring to the "arguments array." Keep in mind,however, that arguments is not really an array; it is an Arguments object. Each Arguments object defines numbered array elements and a length property, but it is not technically an array -- it is better to think of it as an object that happens to have some numbered properties

function f(x) {

    alert(x);             // Displays the initial value ofthe argument

    arguments[0] = null;  // Changing the array element also changes x

    alert(x);             // Now displays "null"

}

4. 函数call 和apply

f.call(o, 1, 2);

This is similar tothe following lines of code:

o.m = f;

o.m(1,2);

delete o.m;


The apply( ) methodis like the call( ) method, except that the arguments to be passed to thefunction are specified as an array:

f.apply(o, [1,2]);



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值