問題一覧に戻る
中級functions
問題72: call/apply メソッド

callとapplyメソッドの使い方を学びましょう。これらのメソッドは、関数を呼び出す際にthisコンテキストを動的に指定できます。callとapplyの違いは引数の渡し方で、callは個別に、applyは配列として渡します。これらは、他のオブジェクトのメソッドを借用したり、配列のメソッドを配列風オブジェクトに適用したり、Math.maxなどの可変長引数を取る関数に配列を渡したりする際に非常に有用です。

// call/applyメソッド
function introduce(age) {
return this.name + "は" + age + "歳です";
}

const person1 = { name: "太郎" };
const person2 = { name: "花子" };

// callを使用
const result1 = introduce.(person1, 25);
console.log("callの結果: " + result1);

// applyを使用
const result2 = introduce.(person2, [30]);
console.log("applyの結果: " + result2);

// Math.max with apply
const numbers = [5, 2, 9, 1, 7, 3];
const max = Math.max.(null, numbers);
console.log("最大値: " + max);