JavaScript call, bind and apply simple

According MDN all three methods are very similar, and at the end they produce very similar result.

  • they all accept this object as first parameter.
  • then apply accepts and array of arguments vs bind and call accept a sequence of arguments.

Function.prototype.apply()

The apply() method calls a function with a given this value, and arguments provided as an array

Function.prototype.bind()

The bind() method creates 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

 

const module = {
  getX: function(one, two) {
    return `${this.x} ${one} ${two}`;
  }
};


const obj = {x: '123'};


console.log( "call: ",module.getX.call(obj, 'ONE', 'TWO') );

console.log( "apply: ",module.getX.apply(obj, ['ONE', 'TWO']) );

var newFunc = module.getX.bind( obj, 'ONE', 'TWO');
console.log("bind: ", newFunc());


result should be the same.

call:  123 ONE TWO
apply:  123 ONE TWO
bind:  123 ONE TWO

 

Leave a Reply