What the hack is Call, bind & apply

As Javascript developers, most of the time we are pretty confused about the Call, bind & apply & their use in JavaScript.

So let's try to understand.

1. CALL & APPLY

Both are these methods are simply known as immediately invoked function. What basically it means whenever you defined both these methods on a function it execute immediately as we run the program.

Technically, if we define CALL & APPLY, both are used to execute a function in a different this context. Where this is passed as first argument & the second or subsequent argument (for Call) is treated as arguments


Only difference b/w them is that CALL takes argument as comma separated while apply takes argument as an array with this as first argument.

So syntax wise, we can simply write them as follows -
f.call(<this-context>, a1, a2, a3, ...)
f.apply(<this-context>, [a1, a2, a3, ...])
Where f is a function to be called in respect of a different this context, where in the above case it is showed as <this-context>

Now lets consider a simple example -
var a = 2
function b() {
    return this.a;
}

b() // 1. output 2

b.call() // 2.   output 2

b.apply() //3.   output 2
So as you have seen from the above code that all the calls produce the same result. The reason is that by default if you are simply calling call & apply, then the default this context will be used. In this case the default this context is Window object.

So now let's make a little change to the code
const obj = {
 a: 5
}

b.call(obj) //  output5

b.apply(obj) //  output5
 Now let's further revise the example to see how argument can be used with call & apply
function b(b) {
   return this.a + b;
}

const obj = {
 a: 5
}

b.call(obj, 6) //  output 11

b.apply(obj, [6]) //  output 11
So as you have seen nothing changed in the final output, just was syntax change.
So this is basically only difference b/w
call & apply in terms how they passed arguments to the calling function.

2. bind

So at high level speaking it is also used to attach the different this context to the calling function but it defer the calling & make sure whenever that function is called will be execute in the given binded this context.
function b(b) {
   return this.a + b;
}
var obj = {
 a: 5
}
var c = b.bind(obj, 6)
c(); //  output 11
OR 
var c = b.bind(obj)
c(6); //  output 11
 So this is the way how the function can behave differently when using call, apply & bind.

Comments

Popular posts from this blog

What is MQTT protocol & its use

What is IIFE in Javascript ?