callとapplyの違いは何ですか?質問する

callとapplyの違いは何ですか?質問する

関数を呼び出すためにを使用することFunction.prototype.apply()とを使用することの違いは何ですか?Function.prototype.call()

const func = function() {
    alert("Hello world!");
};

func.apply()func.call()

前述の 2 つの方法にはパフォーマンスの違いがありますか? どちらを使用するのが最適な場合と、その逆の場合とではどちらが最適な場合が異なりますcallapply?

ベストアンサー1

違いは、 ではapply関数をarguments配列として呼び出すことができ、callパラメータを明示的にリストする必要があることです。便利な記憶法は、配列の場合はAカンマの場合はC」です。

MDNのドキュメントを参照してください適用するそして電話

疑似構文:

theFunction.apply(valueForThis, arrayOfArgs)

theFunction.call(valueForThis, arg1, arg2, ...)

ES6では、spread関数で使用する配列ではcall、互換性を確認できますここ

サンプルコード:

function theFunction(name, profession) {
    console.log("My name is " + name + " and I am a " + profession +".");
}
theFunction("John", "fireman");
theFunction.apply(undefined, ["Susan", "school teacher"]);
theFunction.call(undefined, "Claude", "mathematician");
theFunction.call(undefined, ...["Matthew", "physicist"]); // used with the spread operator

おすすめ記事