Functions in JavaScript have certain properties and methods assigned to them by default.

Properties

There are two properties that each function has. Those are length and prototype.

The length property simply returns the number of arguments passed to a function.

The prototype property points to the location of the original reference types of the function (i.e. object) and its methods and properties. Prototype property is used to establish custom reference types which contain custom made or inherited properties and methods.

Methods

Functions have two non-inherited methods. Those methods are apply() and call() and they both are used to set the value of this for the specific scope.

The apply() method accepts two arguments; the scope in which the function runs and the array of arguments. This is how it works:

function addNum(a, b) {  

   return a + b;

}

function applyMath(a, b) {

   return addNum.apply(this, arguments);

}

alert(applyMath(1, 3)); // 4

The call() method is equivalent to the apply() method except that the arguments are passed differently. While the first argument is still the scope as before, the rest of them are arguments passed directly and separated with commas; like this:

function apply(Math(a, b) {

   return addNum.call(this, a, b);

}

The real advantage in using these methods is their ability to detect the scope in which the function runs. The example in the editor below shows how a call() method may be applied in real life.

The inherited methods, toLocaleString() and toString(), returns the function's code, while valueOf() returns the function itself.

Example

Example with function call() method and scope:

 

›› go to examples ››