Home > Software design >  Understanding the bind method. Reference vs value
Understanding the bind method. Reference vs value

Time:06-21

I don't know if this is a dumb question, but i will ask it anyways.

I saw in a javascript course that we can use the bind method on functions to create basically the same functions but more specific. So like this for example:

const addTax = (rate, value) => value   value * rate;

                           null because we don't need this 
const addVAT = addTax.bind(null, 0.23); 

So basically what we're doing here is that we create a new function called addVAT based on the addTax function but the difference is that we set the rate hardcoded at 0.23.

Now to my question: Since functions are objects and objects are passed by reference, shouldn't the addTax function become now the addVAT function because they both point to the same reference, just like here?:

const person = {
  name: 'test',
};
const person1 = person;
person1.age = 20;

Because when we initalize person1 to person and when we add the property age to person1 it also adds to person

CodePudding user response:

No.


First you create a function and assign it to addTax

const addTax = (rate, value) => value   value * rate;

Then you call the bind method of that function and assign its return value to addVAT.

const addVAT = addTax.bind(null, 0.23); 

The purpose of the bind method is to create a new function and return it.

It doesn't just return the original function (which would be pointless).

The value of addVAT is the new function created by bind.

CodePudding user response:

Bind returns a new function, with some added capabilities.

  • fix the value of this keyword
  • fix the value of one or more arguments.

const addTax = (rate, value) => value   value * rate;
const addVAT = addTax.bind(null, 0.23);
const addVAT1 = addTax;


console.log(addTax === addVAT) // false
console.log(addTax === addVAT1) // true


// to understand why bind is returning new function see the polyfill of bind. 
// This polyfill might not be the correct implementation but it will server the purpose

Function.prototype.myBind = function(context, ...args) {
  // "this" is original function on which bind is called, addTax in your case
  const fun = this;

  // returned funtion when you call bind, addVAT in your case
  return function(...newArgs) {

    // when addVAT is called
    // orignal function is executed here
    return fun.apply(context, [...args, ...newArgs])
  }
}


const myAddVAT = addTax.myBind(null, 0.23);
console.log(myAddVAT(2))
console.log(addVAT(2))

You can see bind never returns the original function, instead it returns a new function, when that new function is called, then the original function gets executed

  • Related