JavaScript bind() function: How to Handle Context
In this article, I'll show you how to handle context in JavaScript and how to use curried functions to help you improve your programming skills. Let's move on to the bind function.
Bind function
The bind()
function in JavaScript is used to create a new function to change the context, for closed friends this
. The new function can be called with a new context and arguments, making it useful for curried functions.
Here's how to use the bind()
function:
const COLORS = {
black: "#000",
white: "#fff",
blue: "#03a9f4",
red: "#f44336",
orange: "#ff9800",
}
function log(color, background, message) {
if (!this.enabled) return
console.log(`%c${message}`, `background: ${background}; color: ${color}`)
}
const loggerConfig = { enabled: true }
const logger = {
log: log.bind(loggerConfig, COLORS.black, COLORS.white),
info: log.bind(loggerConfig, COLORS.white, COLORS.blue),
warn: log.bind(loggerConfig, COLORS.orange, COLORS.white),
error: log.bind(loggerConfig, COLORS.white, COLORS.red),
}
logger.log("It's time to put the bind function to the test.")
logger.info("Testing the bind function with information colors.")
logger.warn("Yeah! Be careful when binding a function using the warn style.")
logger.error("Oh no! Unfortunately, the most recent test has an error style!")
In this example, we have a logger object with new curried functions to display logger-style messages (info, log, warn, error). When that happens, the function is no longer pure! The function's color, background, and enabled configurations are pre-set.
The output code result is shown above.
Context can be null if there is no intention of using it, which is impure! Take a breath, functional programmers.
Then there's a sample with no context.
const simpleInterest = (principalValue, interestRate, period) => principalValue * interestRate * period
const selicInterestRate = 1.1375
const principalValue = 1000
const yearPeriod = 1
const calcSimpleInterest = simpleInterest.bind(null, principalValue, selicInterestRate)
const value = calcSimpleInterest(yearPeriod)
console.log(value)
// 1137.5
In the preceding example, we have a function that calculates simple interest; the current interest rate in Brazil is 13.75% (2023), which is good for saving money 😃 but bad for purchasing things 😟.
Returning to the code, the interest rate and principal amount are calculated to apply simple interest and obtain a new value.
Finally
Today I bring this topic to the table to help you understand the JavaScript prototypes. We used to design classes using prototype syntax; now, there are more elegant and modern techniques, but keep in mind that classes are translated to prototypes, so understanding JavaScript core and principles is essential.
Bind can be used to curry a function; this principle is the foundation of @decorators, and it applies to any programming language.
So make sure your kernel 🧠 is up to date! God bless 🙏🏿 you and see you later!
Time for feedback!