Tuesday, January 15, 2013

Javascript – Call & Apply



Call and apply are methods for invoking a function. Generally a function can be invoked directly with its name or callback reference.
Call and apply functions help to invoke a function, but also passing a object that would be considered as the current object while executing the target function.
Hence a function would behave specific to the provided object.
Below is an example,
Syntax :
[Function Name].call([object],[arg1],[arg2]…)
<script>
    MyFunction = function (name) {
        this.name = name;
    }

    MyName = function (funcName) {
//this.name, is the property value read from the provided object context
        alert(funcName + " - My Name Is : " + this.name);
    }

    var f1 = new MyFunction();
    f1.name = "n1";

  //Invoking the function, passing the object
    MyName.call(f1, 'F1');

    var f2 = new MyFunction("n2");
  //Invoking the function, passing the object

    MyName.call(f2, 'F2');
</script>



 

Apply function is similar as like call function, but instead of proving the arguments each while calling the function the arguments can be sent as an array.
The approach of sending an array rather than passing each argument individually is, it is not really much required to bother about the method signature changes.
So if there are any additional parameters, these parameters can be added to the array and sent as a single parameter.
Below is an example,
Syntax :
[Function Name].apply([object],[[arg1],[arg2]…])
<script>
    MyFunction = function (name) {
        this.name = name;
    }

    MyName = function (funcName,age) {
        alert(funcName + " - My Name Is : " + this.name+' and age : '+age);
    }

    var f1 = new MyFunction();
    f1.name = "n1";
    MyName.apply(f1, ['F1',20]);

    var f2 = new MyFunction("n2");
    MyName.apply(f2, ['F2',30]);
</script>


 

No comments: