Kaunia
Functions in JavaScript are powerful—not just for encapsulating logic, but also for controlling execution context and retaining private state. In this guide, you’ll learn how to:
1. Function Call with call()
The call() method lets you invoke a function with an explicit this value and individual arguments.
Syntax:
Example:
In this example, this inside say becomes user.
apply() is similar to call(), but instead of listing arguments one by one, you pass them as an array.
You often use apply() when you have an array of values you want to pass as arguments.
The bind() method returns a new function with a bound this value and optionally preset initial arguments.
Here, double is a new function where multiply is bound to always use 2 as the first argument. You can still pass the second argument.
bind() is especially useful when passing methods as callbacks where you want to preserve the intended this.
A closure is a function that has access to variables from its outer lexical scope even after that outer function returns. Closures let you create private variables and maintain state in a clean way.
Here, the inner function retains access to count, even after makeCounter() has finished executing. That retained scope is the closure.
Closures are foundational in JavaScript patterns such as data encapsulation, factories, module patterns, memoization, and more.
Understanding how to call functions with call, apply, and bind gives you fine control over execution context. Coupled with closures, you can build powerful, flexible, and maintainable JavaScript code.
Type the number that you see in image.
Aespa Concerts & Events | Tickets, Dates & Festival Info
aespa-concerts
Help Africa Charity | Donate & Support Sustainable Change
help-africa-0
Buckingham Palace
buckinghampalace
Virtual Club UK | Online Parties, DJs & Live Events
virtual-club-uk
IT Services for Businesses Reliable Tech Solutions and Support
it-service-0