bind in JS
Function.prototype.bind()
The bind() method returns a new function that, when called,
- has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
What's here for us to learn this bind method:
1) How it sets the this keyword for the returned function . 2) How it arranges the arguments while calling returned function. [Pre Configuring the function arguments]
How arguments are arranged by bind() method:
Whatever arguments we provide in the bind(this,args) methods those will be precded by other additional arguments that we provide while calling the returned function.
Ex:
function Combine(Showresult,Optype,args)
{
let sum=args;
let res=0;
console.log(sum);
for(elememt of sum)
{
if(Optype=="ADD")
res+=elememt;
if(Optype=="SUB")
res-=elememt;
}
Showresult(res);
}
function Showresult(MesgText,res)
{
console.log(MesgText+res);
}
Combine(Showresult.bind(this,"this addtion is "),"ADD",[7,9,6,5,8,9]);
Combine(Showresult.bind(this,"this substraction is "),"SUB",[7,9,6,5,8,9]);