JavaScriptにおけるオブジェクトの種類と作成方法

JavaScriptでは、オブジェクトはプロパティ(静的特徴)とメソッド(動的動作)をまとめて扱うデータ構造です。 オブジェクトは主に以下の3種類に分類されます:
  • 組み込みオブジェクト:ECMAScript仕様で定義されており、どの実行環境でも利用可能。例:Math、String、Number、Boolean、Function、Objectなど。
  • ホストオブジェクト:実行環境(主にブラウザ)が提供するもの。例:BOMやDOM関連のオブジェクト。
  • ユーザー定義オブジェクト:開発者が独自に作成するオブジェクト。

オブジェクトリテラルによる定義

直接記述して非空のオブジェクトを作成できます:

const smartphone = {
    color: 'black',
    weight: '188g',
    screenSize: 6.5,
    makeCall: function(contact) {
        console.log(`通話先: ${contact}`);
    },
    sendMessage: function(text) {
        console.log(`送信メッセージ: ${text}`);
    },
    playVideo: function() {
        console.log('動画を再生中');
    },
    playMusic: function() {
        console.log('音楽を再生中');
    }
};

console.log(`色: ${smartphone.color}`);
console.log(`重さ: ${smartphone['weight']}`);
console.log(`画面サイズ: ${smartphone.screenSize}`);

smartphone.makeCall('張三');
smartphone.sendMessage('こんにちは');
smartphone.playVideo();
smartphone.playMusic();

new Object()による作成

コンストラクタを使って空のオブジェクトを生成し、後からプロパティやメソッドを追加することも可能です:

const person = new Object();
person.name = '劉備';
person.gender = '男性';
person.age = 32;
person.greet = function() {
    console.log('こんにちは!');
};
person.greet();

コンストラクタ関数によるインスタンス生成

再利用可能なオブジェクトのテンプレートとしてコンストラクタ関数を使用できます:

function Learner(fullName, gender, years) {
    this.fullName = fullName;
    this.gender = gender;
    this.years = years;
    this.displayInfo = function() {
        console.log(`名前: ${this.fullName}`);
        console.log(`性別: ${this.gender}`);
        console.log(`年齢: ${this.years}`);
    };
}

const learner1 = new Learner('喬峰', '男性', 28);
learner1.displayInfo();

const learner2 = new Learner('段誉', '男性', 23);
learner2.displayInfo();

タグ: javascript オブジェクト コンストラクタ関数

8月8日 22:14 投稿