javascript funciton methods :call() and apply()

Standard

ECMAScript specifies two methods that are defined for all functions,

1. call()

2. apply().

These methods allow to invoke a function as if it were a method of some other object.Because functions are objects they can have their own properties and methods, and we can treat them like data.Let’s see the below code:
var y= 'hi, i am defined in global object';
function g() {
alert(this.y);
}
g();

Here we have a global function by the name of g(). g() uses the ‘this’ keyword to reference y, but don’t invoke the function through an instance of an object.So what object does ‘this’ reference? ‘this’ will reference the global object.The global object is where we defined the variable y.The above code does work and will show the message ‘hi, i am defined in global object’ in a dialog.

var y= 'hi, globally defined';
var obj = {y:'property of obj object'};
function g() {
alert(this.y);
}
g(); // 'hi, globally defined'
g.call(obj); // 'property of obj object'

The first invocation of g() will display the message of ‘hi, globally defined‘, because this references the global object. The second invocation (via the call method) however, will display the string ‘property of obj object‘ which is the value of the y property inside object obj. The call() method invokes the function and uses its first parameter as the this pointer inside the body of the function. In other words – we’ve told the runtime what object to reference as this while executing inside of function g().

We can also pass arguments to the target function via call():
var y= 'hi, globally defined';
var obj = {y:'property of obj object'};
function g(msg) {
alert(msg);
alert(this.y);
}
g('invoking g...');
g.call(obj,'invoking via call() method...');

The apply() method is identical to call(), except apply() requires an array as the second parameter. The array represents the arguments for the target method.
var y= 'hi, globally defined';
var obj = {y:'property of obj object'};
function g(msg) {
alert(msg);
alert(this.y);
}
g('invoking g...');
g.apply(obj,['invoking via apply() method...']);

From this post we can learn how to pass the arguments within apply method.

Leave a comment