7.5 Function Properties and Methods
We've seen that functions can be used as data values in JavaScript programs and that they can be created with the Function( ) constructor. These are sure signs that functions are actually represented by a type of JavaScript object, the Function object. Since functions are objects, they have properties and methods, just like the String and Date objects, for example. Now that we've discussed the call and Arguments objects that are used in the context of function invocation, let's turn to the Function object itself. 7.5.1 The length Property
As we've seen, within the body of a function, the length property of the arguments array specifies the number of arguments that were passed to the function. The length property of a function itself, however, has a different meaning. This read-only property returns the number of arguments that the function expects to be passed -- that is, the number of parameters it declares in its parameter list. Recall that a function can be invoked with any number of arguments, which it can retrieve through the arguments array, regardless of the number of parameters it declares. The length property of the Function object specifies exactly how many declared parameters a function has. Note that unlike arguments.length, this length property is available both inside and outside of the function body. The following code defines a function named check( ) that is passed the arguments array from another function. It compares the arguments.length property to the Function.length property (which it accesses as arguments.callee.length) to see if the function was passed the number of arguments it expected. If not, it throws an exception. The check( ) function is followed by a test function f( ) that demonstrates how check( ) can be used: 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;} 
The length property of the Function object is standardized by ECMAScript v1 and implemented in JavaScript 1.1 and later.[3] [3] In Netscape 4.0, a bug prevents this property from working correctly unless the language attribute of the <script> tag is explicitly set to "JavaScript1.2". 7.5.2 The prototype Property
Every function has a prototype property that refers to a predefined prototype object. This prototype object comes into play when the function is used as a constructor with the new operator; it plays an important role in the process of defining new object types. We'll explore this property in detail in Chapter 8. 7.5.3 Defining Your Own Function Properties
When a function needs to use a variable whose value persists across invocations, it is often convenient to use a property of the Function object, instead of cluttering up the namespace by defining a global variable. For example, suppose we want to write a function that returns a unique identifier whenever it is invoked. The function must never return the same value twice. In order to manage this, the function needs to keep track of the values it has already returned, and this information must persist across function invocations. We could store this information in a global variable, but that is unnecessary because the information is used only by the function itself. It is better to store the information in a property of the Function object. Here is an example that returns a unique integer whenever it is called: // 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++;} 
7.5.4 The apply( ) and call( ) Methods
ECMAScript v3 defines two methods that are defined for all functions, call( ) and apply( ). These methods allow you to invoke a function as if it were a method of some other object. (Note that we have not discussed methods yet; you may find this section more understandable once you have read Chapter 8.) The first argument to both call( ) and apply( ) is the object on which the function is to be invoked; this argument becomes the value of the this keyword within the body of the function. Any remaining arguments to call( ) are the values that are passed to the function that is invoked. For example, to pass two numbers to the function f( ) and invoke it as if it were a method of the object o, you could use code like this: f.call(o, 1, 2); 
This is similar to the following lines of code: o.m = f;o.m(1,2);delete o.m; 
The apply( ) method is like the call( ) method, except that the arguments to be passed to the function are specified as an array: f.apply(o, [1,2]); 
For example, to find the largest number in an array of numbers, you could use the apply( ) method to pass the elements of the array to the Math.max( ) function:[4] [4] This example assumes we are using the ECMAScript v3 Math.max( ) function, which accepts an arbitrary number of arguments; the ECMAScript v1 version of the function accepts only two arguments. var biggest = Math.max.apply(null, array_of_numbers); 
The apply( ) method is implemented in JavaScript 1.2, but the call( ) method is not implemented until JavaScript 1.5. 
 var data = [1,2,3,4,5,6,7,8];alert(Math.max.apply(null, data))

解决方案 »

  1.   

    这个是低版本浏览器的解决方法,看懂这个了,就完全理解了,apply和call的作用http://blog.csdn.net/muxrwc/archive/2007/10/31/1859284.aspx
      

  2.   


    var o = {
       "a":'a',
       "b":'b'
    };
    function caller(myParam1,myParam2)
    {
        alert(this.a+' '+this.b+' '+myParam1+' '+myParam2);
    }
    caller.call(o,'myParam1','myParam2');
    caller.apply(o,['myParam1','myParam2']);
      

  3.   

      JavaScript为函数对象定义了两个方法:apply和call,它们的作用都是将函数绑定到另外一个对象上去运行,两者仅在定义参数的方式有所区别:Function.prototype.apply(thisArg,argArray);
    Function.prototype.call(thisArg[,arg1[,arg2…]]);
      从函数原型可以看到,第一个参数都被取名为thisArg,即所有函数内部的this指针都会被赋值为thisArg,这就实现了将函数作为另外一个对象的方法运行的目的。两个方法除了thisArg参数,都是为Function对象传递的参数。下面的代码说明了apply和call方法的工作方式://定义一个函数func1,具有属性p和方法A
    function func1(){
          this.p="func1-";
          this.A=function(arg){
                alert(this.p+arg);
          }
    }
    //定义一个函数func2,具有属性p和方法B
    function func2(){
          this.p="func2-";
          this.B=function(arg){
                 alert(this.p+arg);
          }
    }
    var obj1=new func1();
    var obj2=new func2();
    obj1.A("byA");    //显示func1-byA
    obj2.B("byB");    //显示func2-byB
    obj1.A.apply(obj2,["byA"]); //显示func2-byA,其中[“byA”]是仅有一个元素的数组,下同
    obj2.B.apply(obj1,["byB"]); //显示func1-byB
    obj1.A.call(obj2,"byA");  //显示func2-byA
    obj2.B.call(obj1,"byB");  //显示func1-byB
      可以看出,obj1的方法A被绑定到obj2运行后,整个函数A的运行环境就转移到了obj2,即this指针指向了obj2。同样obj2的函数B也可以绑定到obj1对象去运行。代码的最后4行显示了apply和call函数参数形式的区别。
    Function.apply() 在提升程序性能方面的技巧。我们先从 Math.max() 函数说起,  Math.max后面可以接任意个参数,最后返回所有参数中的最大值。比如 
    alert(Math.max(5,8))   //8
    alert(Math.max(5,7,9,3,1,6))   //9但是在很多情况下,我们需要找出数组中最大的元素。
    var arr=[5,7,9,1]
    alert(Math.max(arr))    //   这样却是不行的。一定要这样写
    function getMax(arr) {
    var arrLen = arr.length;
    for (var i = 0, ret = arr[0]; i < arrLen; i++) {
    ret = Math.max(ret, arr[i]);
    }
    return ret;
    }这样写麻烦而且低效。如果用 apply呢,看代码:
    function getMax2(arr){
        return Math.max.apply(null,arr)
    }两段代码达到了同样的目的,但是getMax2却优雅,高效,简洁得多。