Essentially, the bind
function creates a new function with predetermined parameters based on the original function it is called upon.
The first parameter of bind
holds special significance and will be further discussed. Additional parameters passed to bind
are "baked in" to the resulting function.
Consider the function addTwoNumbers
:
function addTwoNumbers(a, b) {
return a + b
}
As addTwoNumbers
is a function object, we can utilize bind
to create a new function by specifying parameters:
var addThree = addTwoNumbers.bind(null, 3) // null is used as the first parameter since "this" is not required
The newly created function addThree
now only requires one argument and functions similarly to:
function addThree(b) {
return addTwoNumbers(3, b)
}
Therefore, calling addThree(4)
would yield 7
.
The initial param supplied to bind
determines the value of this
within the scope of the new function.
For instance, consider the following function:
function printTheValueOfThis() {
console.log(this)
}
var printHello = printTheValueOfThis.bind('hello')
printHello() // this will output "hello" to the console
Within your code snippet, the targeted function is console.log
and the "error information" is bound as the second argument.
An alternate way to represent this concept is through:
db.on('error', (someUnusedArg, errorInfo) => {
console.log('connection error:', errorInfo)
});
Various resources discuss the bind
function in depth. For further reading, you may explore: bind Method (Function)