JavaScript学习(三)

1.函数定义在解析时发生,而不是在运行时发生

 

 

alert(f(4));     // Displays 16. f( ) can be called before it is defined.
var f = 0;       // This statement overwrites the property f.
function f(x) {  // This "statement" defines the function f before either
    return x*x;  // of the lines above are executed.
}
alert(f);        // Displays 0. f( ) has been overwritten by the variable f.

 上面这个例子也说明了,只要在同一个作用域定义了的函数或者变量,在同一个作用域里任何位置都是可以调用的

 

 

2.调用对象:

调用对象将作为函数的一个属性

 

 

3.调用函数的特殊属性:

  arguments

 

 

function f(x) {
    print(x);             // Displays the initial value of the argument
    arguments[0] = null;  // Changing the array element also changes x!
    print(x);             // Now displays "null"
}

 

arguments的属性callee:用来引用当前正在执行的函数

 

计算阶乘的函数:

 

 

function(x) {
    if (x <= 1) return 1;
    return x * arguments.callee(x-1);
}
 

4.Function 的属性:

 

 

 length:(同arguments.callee.length)

下面一个函数实现了校验函数的实际参数个数是否满足需要:

 

function check(args) {
    var actual = args.length;           // The actual number of arguments
    var expected = args.callee.length;  // The expected number of arguments
    if (actual != expected) {  // Throw an exception if they don't match
        throw new Error("Wrong number of arguments: expected: " +
                        expected + "; actually passed " + actual);
    }
}

function f(x, y, z) {
    // Check that the actual # of args matches the expected # of args
    // Throw an exception if they don't match
    check(arguments);
    // Now do the rest of the function normally
    return x + y + z;
}

 等同于(在某一个特定函数,知道形参的情况下):

 

 

function f(x, y, z)
{
    // First, verify that the right number of arguments was passed
    if (arguments.length != 3) {
        throw new Error("function f called with " + arguments.length +
                        "arguments, but it expects 3 arguments.");
    }
    // Now do the actual function...
}
 

5.函数“静态”属性

 

不用全局变量得到一个递增的数

 

 

// Create and initialize the "static" variable.
// Function declarations are processed before code is executed, so
// we really can do this assignment before the function declaration.
uniqueInteger.counter = 0;

// Here's the function. It returns a different value each time
// it is called and uses a "static" property of itself to keep track
// of the last value it returned.
function uniqueInteger() {
    // Increment and return our "static" variable
    return uniqueInteger.counter++;
}
 

 

6.方法apply()和call()

 

call和apply函数的第一个参数都是要调用的对象

 

 

f.call(o, 1, 2);

 等同于

 

 

o.m = f;
o.m(1,2);
delete o.m;
 

apply和call相似,区别是参数变成数组的形式了

 

 

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

 

JavsScript1.2实现了apply,JavaScript1.5才实现 call

 

 

你可能感兴趣的:(JavaScript,F#,REST)