Tuesday, November 8, 2011

Callback in javascript

We create function normally to get arguments and return specific type of value in most of the programming languages. But functions in javascript behaves different. Function in javascript are objects that has predefined properties.

In javascript we can pass function as an argument and execute that passed function from the called function. We can execute passed function from the called function using the predefiend function property "call". The first parameter to the call back function acts as scope of the function and other parameters can be accessed normal way.

Lets take an example. Here function named "func" is the main function that takes an argument. Inside the function object "p" is created that has two property named "name" and "lastname". Similarly "company" object is created with property named "name" and "address". Also variable named "fullname" is created.

Another function test is created with two parameters "param1" and "param2". Here alert is given for the passed parameters and scope provided to the test from the called function.

Now we call the function "func" with the function "test" as parameter.
The line
a.call(p,fullname,company);
calls back the passed function "test". The first parameter "p" here acts as scope of the function during callback and can be accessed using keyword "this" as done on lline
alert(this.name+' ' +this.lastname);



func=function(a){
p={};
p.name='myname';
p.lastname='mylastname';
var fullname= 'abc xyz ';
company = new Object();
company.name='My Tech P. Ltd';
company.address='Nepal';
a.call(p,fullname,company);
}

test=function(param1,param2){
alert(param1);
alert(param2.name+param2.address);
alert(this.name+' ' +this.lastname);
}

func(test);

No comments: