Today’s post will be about methods to call functions, which are .call, .apply and .bind. The difference between .call and .apply is the way you receive parameter.
.call receives paramter one by one while .apply receives it as an array.
Call & Apply
Let’s check out some examples of call and apply.
Both call and apply carry out functions, but the parameters are passed in differently.
When apply receives an array and “this” does not mean anything, put in null.
.bind does not carry out function like call or apply. It returns the function that “this” is binded to.
When bindit is called, the add function binds obj as this and calls the function. It only calls and does not execute like closure. Therefore, bindit will give you a result of 10. bind is usually used to bind the value of “this” to something.
The code above shows that “this” is water, which is an instance of the class whatisprice.
When do we use this?
When do we use bind?
When the code above is called, can 30 be printed after 5 seconds? The answer is no.
When setTimeout is called, the value of this is window. Therefore, since water is not “this”, an error will appear. To solve this, we use bind to set the value of this as water.
When we bind the value of this as water, the code works!
Currying is also possible with bind!
The code above (Joshua) returns the function greeting. However, “Joshua” is binded inside that function. Since the value of “this” was not set, the first parameter of bind is null.
Remember! bind is used to set the value of “this”