DEV Community

Dan-Vy Le
Dan-Vy Le

Posted on

MJSQ 101: Function.prototype.bind

More JavaScript Questions 101(MJSQ 101):

Continuing from my original blog post, I give you more javascript 101 questions answered!:

Question this week:

Explain Function.prototype.bind

Taken word-for-word from MDN:

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 = {
  x: 42,
  getX: function() {
    return this.x;
  }
}

const unboundGetX = module.getX;
console.log(unboundGetX()); // The function gets invoked at the global scope
// expected output: undefined

const boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// expected output: 42


In their example, the unboundGetX variable cannot call on the module variable's getX function until it has been bound with the Function.prototype.bind method.

This approach would be good when you're wanting to bind the value of this to pass into other functions.

References
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

That's all for today, please leave any comments/questions/corrections in the comments. Thanks!

Sources:

Huge huge thanks to github user: yangshun for aggregating the most popular JS, CSS and HTML questions and giving us his answers to it. My weekly blog posts are to go over several questions at a time to reinforce my knowledge of fundamental javascript as I grow my expertise in it. Many of my blog will be paraphrasing if not direct quotes from his github. Find his tech interview handbook here and please support him!

And an additional thank you to Flatiron alum: Marissa O. who is a badass developer at Forbes magazine for directing me to his blog!

Discussion (0)