関数を呼び出すためにを使用することFunction.prototype.apply()
とを使用することの違いは何ですか?Function.prototype.call()
const func = function() {
alert("Hello world!");
};
func.apply()
対func.call()
前述の 2 つの方法にはパフォーマンスの違いがありますか? どちらを使用するのが最適な場合と、その逆の場合とではどちらが最適な場合が異なりますcall
かapply
?
ベストアンサー1
違いは、 ではapply
関数をarguments
配列として呼び出すことができ、call
パラメータを明示的にリストする必要があることです。便利な記憶法は、「配列の場合はA、カンマの場合はC」です。
疑似構文:
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