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
1var myObj = {
2
3 specialFunction: function () {
4
5 },
6
7 anotherSpecialFunction: function () {
8
9 },
10
11 getAsyncData: function (cb) {
12 cb();
13 },
14
15 render: function () {
16 var that = this;
17 this.getAsyncData(function () {
18 that.specialFunction();
19 that.anotherSpecialFunction();
20 });
21 }
22};
23
24myObj.render();
and this code achieve the same
1render: function () {
2
3 this.getAsyncData(function () {
4
5 this.specialFunction();
6
7 this.anotherSpecialFunction();
8
9 }.bind(this));
10
11}
.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
.
1var foo = {
2 x: 3
3}
4
5var bar = function(){
6 console.log(this.x);
7}
8
9bar(); // undefined
10
11var boundFunc = bar.bind(foo);
12
13boundFunc(); // 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.