Each argument passed into bind will be set as the parameter prematurely. This process is called Partial Application. It is often used in Functional Programming.
Example:
Let’s say you have a sayName function.
function sayName (firstName, lastName) {
console.log(`${firstName} ${lastName}`)
}
You want to set firstName to zell. You can use bind to do this.
Here, we pass null as this because we don’t need to use this inside sayName. We will also pass Zell as an argument.
const sayZell = sayName.bind(null, 'Zell')
You can then call sayZell to run the function.
sayZell('Liew') // Zell Liew
Functional Programming is out of scope for this course so we’ll stop talking about it here. You can google for more information if you’re interested :)
Call
Call lets you change this as you call a function. It has the same syntax as bind.
aFunction.call(this, arg1, arg2)
In this case, arguments are compulsory since you call the function immediately.
Apply is useful when you need to pass arguments from one function into another. But it can be replaced by a combination of call, and Rest + Spread operators.
Example:
JavaScript has an arguments variable that keeps track of all arguments passed in as an array.
function sayThings () {
console.log(arguments)
}
sayThings('Happy', 'birthday')
We shouldn’t use arguments because arguments make the function less-explicit. We don’t know if any arguments need to be passed into the function before inspecting the code within.
It’s much better to use ES6 rest and spread operators. Once you see ...args, you know it means “the rest of the arguments goes into this array”.
function sayThings (...args) {
console.log(...args)
}
sayThings('Happy', 'birthday')