JavaScript: this
, arguments
, new
について
this
とは?
this
は、関数が呼び出された際の文脈(コンテキスト)を指します。関数の呼び出し方によって、this
が何を指すかが変わります。
例1: オブジェクト内のメソッドでのthis
const obj = {
name: 'Alice',
greet: function () {
console.log(this.name); // 'Alice'
}
};
obj.greet();
例2: 通常の関数でのthis
function showThis() {
console.log(this); // グローバルオブジェクト(strictモードではundefined)
}
showThis();
例3: 矢印関数でのthis
const obj = {
name: 'Alice',
greet: () => {
console.log(this.name); // 外側のスコープのthisを指すためundefined
}
};
obj.greet();
arguments
とは?
arguments
は、通常の関数内で利用できる特別なオブジェクトで、関数に渡されたすべての引数を保持します。
例
function sum() {
console.log(arguments); // 配列のようなオブジェクト
return Array.from(arguments).reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3)); // 6
矢印関数での代替
const sum = (...args) => args.reduce((total, num) => total + num, 0);
console.log(sum(1, 2, 3)); // 6
new
とは?
new
は、コンストラクタ関数やクラスを基に新しいオブジェクトを作成するためのキーワードです。
例
function Person(name, age) {
this.name = name;
this.age = age;
}
const person1 = new Person('Alice', 25);
console.log(person1); // { name: 'Alice', age: 25 }
まとめ
キーワード | 説明 | 主な特徴 |
---|---|---|
this | 関数の呼び出し方によって異なるコンテキストを参照します。 | オブジェクトのメソッドやスコープを示す。 |
arguments | 関数に渡されたすべての引数を保持します。 | 通常の関数でのみ使用可能(矢印関数では使用不可)。 |
new | コンストラクタ関数やクラスを基に新しいオブジェクトを作成します。 | this を新しいオブジェクトにバインド。 |