function apply()

Description

functionName.apply() calls the function with this value, and set this inside the function body.

The apply() method accepts two arguments:

  • the value of this inside the function
  • an array of arguments. It may be an instance of Array, or the arguments object.

Example


function sum(num1, num2){/*from   www  .  j  av a  2 s.  c om*/
   return num1 + num2;
}

function callSum1(num1, num2){
   return sum.apply(this, arguments);    //passing in arguments object
}

function callSum2(num1, num2){
   return sum.apply(this, [num1, num2]); //passing in array
}

console.log(callSum1(10,10));   //20
console.log(callSum2(10,10));   //20

callSum1() executes the sum() method, passing in this as the this value and also passing in the arguments object.

The callSum2() method also calls sum(), but it passes in an array of the arguments instead.

The code above generates the following result.

Augment this

apply() can augment the this value inside of the function.


<!-- w  w  w  .  j a  va2 s.co m-->
<!DOCTYPE HTML>
<html>
<head>
  <script type="text/javascript">
    window.myName = "XML";
    var o = { myName: "CSS" };
    
    function printMyName(){
       console.log(this.myName);
    }
    
    printMyName();            //XML
    
    printMyName.apply(this);   //XML
    printMyName.apply(window); //XML
    printMyName.apply(o);      //CSS
  </script>
</head>
<body>
</body>
</html>

Click to view the demo

printMyName() is defined as a global function, and when it's called in the global scope, it displays "XML" because this.myName evaluates to window.myName.

You can then call the function explicitly in the global scope by using printMyName.call(this) and printMyName.call(window), which both display "XML". Running printMyName.call(o) switches the context of the function such that this points to o, resulting in a display of "CSS".





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions