JavaScript: this, arguments, newについて

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を新しいオブジェクトにバインド。

 

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です