4.Function Call Patterns

Introduction

What ?, a separate topic about function call, yes it might sound silly but we feel that there are some technique to discuss that you might not aware of, so lets begin.

You know what function call means and how to define a method and call it , In this section will discuss about the various options and call a function and how function call in certain pattern is treated in javascript.

Call a function

There is one common function call pattern which we use in our day to day life. and it is at the core of javascript system.

1 [variableValue](args)

For example consider a function

1 function foo()
2 {
3 }
4 
5 //or
6 
7 var foo=function()
8 {
9 }

When you declare like this there is a variable called foo which is created and a function is attached to it, so that implies the function call to be like below.

1 foo();  //Which implies pattern [variableValue](args);

Self invocation function

Function can be self invoked, consider the below example

1 (function foo()
2 {
3 })()

Before the invocation brackets , the function foo wrapped inside another bracket is treated as a value which means the above is similar to the below statement

1 (foo)()

This show’s the fact that javascript is very dynamic in nature and this made us fall in love with it.

Call and Apply

As explained in the previous sections, when a function is invoked, there are two things associated with it, context and arguments. Context refers to this inside a function, and arguments is the values passed to that function.

Call and Apply is the function in Function object which is used to invoke the function with specific context and arguments.

 1 function foo()
 2 {
 3     //consoles the context objects
 4     console.log('context:',this);
 5     for(var i in arguments)
 6     {
 7         //consoles the argument variable name
 8         console.log(i);
 9     }
10 }
11 
12 var thisObj={};
13 
14 foo.apply(thisObj,[1,2,3]);
15 foo.call(thisObj,1,2,3);
16 
17 //result
18 //context
19 //window obj
20 //1
21 //2
22 //3

In the above example function foo is implemented to console the context passed to that function and list of arguments.

The only difference between call and apply is that apply accepts the function argument as a single array, and with call it accepts each arguments as single value , you can see that in the above example.