What is the use of the JavaScript 'bind' method?
Bind creates a new function that will force the this
inside the function to be the parameter passed to bind()
.
Here's an example that shows how to use bind
to pass a member method around that has the correct this
:
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
You can also add extra parameters after the 1st (this
) parameter and bind
will pass in those values to the original function. Any additional parameters you later pass to the bound function will be passed in after the bound parameters:
// Example showing binding some parameters
var sum = function(a, b) {
return a + b;
};
var add5 = sum.bind(null, 5);
console.log(add5(10));
Which prints out:
15
Check out JavaScript Function bind for more info and interactive examples.
Update: ECMAScript 2015 adds support for =>
functions. =>
functions are more compact and do not change the this
pointer from their defining scope, so you may not need to use bind()
as often. For example, if you wanted a function on Button
from the first example to hook up the click
callback to a DOM event, the following are all valid ways of doing that:
var myButton = {
... // As above
hookEvent(element) {
// Use bind() to ensure 'this' is the 'this' inside click()
element.addEventListener('click', this.click.bind(this));
}
};
Or:
var myButton = {
... // As above
hookEvent(element) {
// Use a new variable for 'this' since 'this' inside the function
// will not be the 'this' inside hookEvent()
var me = this;
element.addEventListener('click', function() { me.click() });
}
};
Or:
var myButton = {
... // As above
hookEvent(element) {
// => functions do not change 'this', so you can use it directly
element.addEventListener('click', () => this.click());
}
};
What does `bind(this)` mean?
It binds the listener of the function to the current class, then when you use this
pointer inside of the onBeforeFirstShow
function, the this
pointer refer to encapsulated class and you can access to its members.
Javascript call() & apply() vs bind()?
I created this comparison between function objects, function calls, call/apply
and bind
a while ago:
.bind
allows you to set the this
value now while allowing you to execute the function in the future, because it returns a new function object.
Why is JavaScript bind() necessary?
Why is JavaScript bind() necessary?
The value of this
is determined by how a function is called. If it is you who calls the function then there is usually no need to use .bind
, since you have control over how to call the function, and therefore its this
value.
However, often it is not you who calls the function. Functions are passed to other functions as callbacks and event handlers. They are called by other code and you have no control over how the function is called, and therefore cannot control what this
will refer to.
If your function requires this
to be set to a specific value and you are not the one calling the function, you need to .bind
the function to a specific this
value.
In other words: .bind
allows you to set the value of this
without calling the function now.
Here is comparison of referring to/calling functions:
+-------------------+-------------------+
| | |
| time of | time of |
|function execution | this binding |
| | |
+-------------------+-------------------+-------------------+
| | | |
| function object | future | future |
| f | | |
| | | |
+-------------------+-------------------+-------------------+
| | | |
| function call | now | now |
| f() | | |
| | | |
+-------------------+-------------------+-------------------+
| | | |
| f.call() | now | now |
| f.apply() | | |
| | | |
+-------------------+-------------------+-------------------+
| | | |
| f.bind() | future | now |
| | | |
+-------------------+-------------------+-------------------+
I'm also wondering why example 3 solves the issue and the difference between example 2 and 3.
Example 1/2 and 3 couldn't be more different. storeMyName
and storeMyName2
contain functions, which are called in the future, whereas storeMyName3
contains the result of calling myName.getName()
at that moment.
Further reading material:
- How does the "this" keyword work?
- MDN - this
- YDKS - this & Object Prototypes
- How to access the correct `this` context inside a callback?
When to use .bind() in JS
In a nutshell, .bind()
returns a new function that when called will call the original function with a specific this
value and (optionally) some new arguments preprended to the argument list.
.bind()
is used when you need to pass a callback (e.g. some sort of function reference), but you want the caller to call your function with a specific this
value. This is most common when your function is actually a method and you want the this
value set to be the a specific object so the method will operate on that specific object . If you don't use .bind()
in those cases, then the this
value will be determined by the caller (not you) and if the caller doesn't set it specifically, it will end up being the global object or (in strict mode) undefined
. If what you were passing was a method that relies on a specific value of this
in order to do its job, it would not work properly with the wrong this
value.
So, if you want to control the value of this
when your callback is called, you can use .bind()
. Internally, .bind()
just creates a small stub function that just remembers the this
value you pass it and calls your function with .apply()
to set the this
value. .bind()
is not magic as it can be done manually too.
.bind()
also has the capability to add extra arguments to the function so, if you want to add arguments beyond what the normal caller of the callback uses, you can specify those with .bind()
too. It creates a stub function that will add these extra arguments and set the this
value.
Let's say you have your Person
object and you want to hook a button up to the .say()
method for a particular Person
object.
<button id="talk">Talk</button>
And, if you tried this javascript:
"use strict";
var bob = new Person("Bob", "Smith");
document.getElementById("talk").addEventListener("click", bob.say);
What you would find is that the say()
method is called, but it would be missing two things. It would be missing the right this
reference (which would be set to the button
object because that's how addEventListener calls its callbacks) and it would be missing the argument that say(message)
expects.
So, you could solve this yourself with your own stub function that calls bob.say()
with all the right arguments:
"use strict";
var bob = new Person("Bob", "Smith");
document.getElementById("talk").addEventListener("click", function(e) {
bob.say("Hello");
});
Or, you could use .bind()
:
"use strict";
var bob = new Person("Bob", "Smith");
document.getElementById("talk").addEventListener("click", bob.say.bind(bob, "Hello"));
There is no magic in .bind()
. It can be entirely simulated in javascript. In fact, here's a polyfill for it from MDN:
if (!Function.prototype.bind) {
Function.prototype.bind = function(oThis) {
if (typeof this !== 'function') {
// closest thing possible to the ECMAScript 5
// internal IsCallable function
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function() {},
fBound = function() {
return fToBind.apply(this instanceof fNOP && oThis
? this
: oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
This may look more complicated than it is because of all the error checking, but it's really just return a new function that combines two sets of arguments and then calls the original function with a specific this
value.
Vanilla Javascript use of bind() with REST parameter
You can't. The event handling system always passes the event.
The callback function itself has the same parameters and return value as the handleEvent() method; that is, the callback accepts a single parameter: an object based on Event describing the event that has occurred, and it returns nothing.
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#the_event_listener_callback
If your goal is to iterate the arguments and treat them all the same then how about:function say(numbers, event)
say.bind(null, [1, 2, 3])
Is there a simple way to understand .bind of JavaScript in plain english?
bind
allows you to change the value of this
in a function. bind
also creates a new function.
var cat = {
name: 'cat',
whatIsThis(){
console.log('this is ' + this.name)
}
}
var dog = {
name: 'dog',
whatIsThis(){
console.log('this is ' + this.name)
}
}
cat.whatIsThis()// this is cat
dog.whatIsThis()// this is dog
var func = cat.whatIsThis.bind(dog)
func()// this is dog
cat.whatIsThis()// this is cat
Related Topics
Creating Multiline Strings in JavaScript
How to Get the Value of Text Input Field Using JavaScript
Send Post Data Using Xmlhttprequest
Detecting an Undefined Object Property
Jquery: Return Data After Ajax Call Success
Escape String For Use in JavaScript Regex
What Does 'Return' Keyword Mean Inside 'Foreach' Function
Deleting Array Elements in JavaScript - Delete VS Splice
All Falsey Values in JavaScript
What Do Multiple Arrow Functions Mean in JavaScript
What Is Event Bubbling and Capturing
Why Does Calling React Setstate Method Not Mutate the State Immediately
Creating a Blob from a Base64 String in JavaScript
What Does the Exclamation Mark Do Before the Function
Client on Node.Js: Uncaught Referenceerror: Require Is Not Defined
Cloud Functions For Firebase Trigger on Time