.bind(), .apply() and .call()

常常忘記這三個在幹嘛所以整理一下日後好查詢。

.bind()

1
func.bind(thisArg[, arg1[, arg2[, ...]]]);

bind doesn’t execute function immediately,
but returns wrapped apply function with certain context (for later execution):

1
2
3
4
5
6
7
8
9
function greeting(name) {
this.hello = this.hello || "Hello";
return `${this.hello}, ${name}!`;
}
const greetingInJapanese = greeting.bind({hello: "こんばんわ"});
greeting("Trina"); // Hello, Trina!
greetingInJapanese("Trina"); // こんばんわ, Trina!

.apply() / .call()

.call() or .apply() invokes the funciton immediately, and modify the context.

1
2
func.call(context, argument1, argument2, ...);
func.apply(context, [argument1, argument2, ...]);

Notice

Beware that arrow functions could not be bound to another context.

MDN: Arrow function #No binding of this

Sources