1.

What is prototypal inheritance ?

Answer»

EVERY function in JavaScript have call, APPLY and bind methods. These methods can be used to set the CUSTOM value of “this” to the execution context of the function.

call
Let’s say that we have an object called obj. It only has one property called num, which has a value of 3. Let’s also make a function called addNumbers

Now, in addNumbers we have this.num. But how do we pass the value obj.num to it. We need to pass it a context, which means the value of “this”. We will do this my call method by passing a first argument as obj, so the “this” is the obj now.

let obj = {num: 3}; let addNumbers = function(a, b, c){   return this.num + a + b + c; }; console.log(addNumbers.call(obj, 1, 4, 6));  //14 

apply
It is totally similar to call, but the only difference is that we can pass array as the second argument. We will use the same code for apply also. But now we have an ARR, to be passed as second argument. 

let obj = {num: 3}; let addNumbers = function(a, b, c){   return this.num + a + b + c; }; let arr = [7, 3, 8]; console.log(addNumbers.apply(obj, arr)); //21

bind
Bind works in a bit different way then call and apply. It works by RETURNING a copy of the function. We will take the returned function in bindFunc and then execute it in the next line.

let obj = {num: 3}; let addNumbers = function(a, b, c){    return this.num + a + b + c; };   let bindFunc = addNumbers.bind(obj); console.log(bindFunc(7, 3, 8)); //21


Discussion

No Comment Found