TASIOMIND.DEV — OPERATIONAL▸▸▸FULL STACK DEVELOPER @ GWQ SERVICEPLUS AG▸▸▸FOUNDER — K8SGPT.AI▸▸▸OPEN SOURCE: ACTIVE▸▸▸DISTRIBUTED SYSTEMS / KUBERNETES / AI▸▸▸RUST + GO + PYTHON▸▸▸FIELD TESTED / STATUS — NOMINAL▸▸▸LOCATION: EUROPE/BERLIN▸▸▸TASIOMIND.DEV — OPERATIONAL▸▸▸FULL STACK DEVELOPER @ GWQ SERVICEPLUS AG▸▸▸FOUNDER — K8SGPT.AI▸▸▸OPEN SOURCE: ACTIVE▸▸▸DISTRIBUTED SYSTEMS / KUBERNETES / AI▸▸▸RUST + GO + PYTHON▸▸▸FIELD TESTED / STATUS — NOMINAL▸▸▸LOCATION: EUROPE/BERLIN▸▸▸

bind

November 25, 2016

bind

bind creates a new function and sets it's scope.

We use .bind() to create a new function and then set it's scope to be bound to whatever was passed to bind.

this code

code
var myObj = {
  specialFunction: function () {},

  anotherSpecialFunction: function () {},

  getAsyncData: function (cb) {
    cb();
  },

  render: function () {
    var that = this;
    this.getAsyncData(function () {
      that.specialFunction();
      that.anotherSpecialFunction();
    });
  },
};

myObj.render();

and this code achieve the same

code
render: function () {

    this.getAsyncData(function () {

        this.specialFunction();

        this.anotherSpecialFunction();

    }.bind(this));

}

.bind() simply creates a new function that, when called, has its this keyword set to the provided value. So, we pass our desired context, this (which is myObj), into the .bind() function. Then, when the callback function is executed, this references myObj.

code
var foo = {
  x: 3,
};

var bar = function () {
  console.log(this.x);
};

bar(); // undefined

var boundFunc = bar.bind(foo);

boundFunc(); // 3

.bind(), .apply() and .call() are all methods used to set the scope of a function. call and apply are immediately executed whereas bind let's you call the function at a later time. bind sets the scope but doesn't execute the function.