Friday, 30 June 2023

Javascript bind, ES7 bind ::

 var myButton = {

  content: 'OK',
  click() {
    console.log(this.content + ' clicked');
  }
};

myButton.click();

var looseClick = myButton.click;
looseClick(); // not bound, 'this' is not myButton - it is the globalThis

var boundClick = myButton.click.bind(myButton);
boundClick(); // bound, 'this' is myButton

Which prints out:

OK clicked
undefined clicked
OK clicked

https://stackoverflow.com/questions/2236747/what-is-the-use-of-the-javascript-bind-method


ES7:
https://stackoverflow.com/questions/31220078/javascript-double-colon-bind-operator


As you know, there is a proposal for a shortcut for .bind() function, so you can write:

::this.handleStuff

and it will work like that in es5:

this.handleStuff.bind(this)

No comments:

Post a Comment