Bind in Node.js

what is console.error.bind that I don"t understand?
Why should I use console.error.bind here?

db.on("error", console.error.bind(console, "error"));

there is an error directly using the console.error ("error") output, isn"t it?

Mar.02,2021

Origin
in JS, a function is very simple, just a function, and the this direction of a function is unknown until it is called.
by default, this points to whoever calls the function.
explain
that is, when the passing function is handed over to someone else for execution, the this points to the new caller for the function.
when console.error (), calls the error function, this points to the console object, but when you pass the error function to something else, this becomes something else.
solve
how to ensure that the direction of this remains the same? The answer is that there is a bind function on the prototype chain of the function, which can set the this point of the function, and it is permanently not allowed to be modified after binding, but it will not change. The first parameter of the bind function is the object that this needs to point to.

later words: syntax sugar () = > {} arrow function
arrow function is directly bound on the current this object, which is equivalent to binding this
() = > {} directly after the definition is completed, which is about equivalent to function () {} .bind (this)
that is to say, when the arrow function is declared, the this point is fixed and will not change in the future.


achieves the same effect
but

console.error.bind(console, 'error')

can be used as a function


is OK, but the second parameter of db.on lets you pass a function, not the return value of the function.
but I think it's OK to write this way

db.on('error', () => { console.error('error') };
Menu