【JavaScript】オブジェクト(クラス)定義とインスタンス化のサンプル
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
//=====Customerオブジェクトの定義===== //コンストラクター var Customer = function(customerId = '0000', name = 'default') { this.customerId = customerId; this.name = name; }; //メソッドの定義 Customer.prototype = { getCustomerId : function() { return this.customerId; }, getName : function() { return this.name; }, //メンバ変数を列挙する printInfo : function() { for (var prop in this) { if (this[prop].toString().match(/function?\{?\}?/)) { continue; } //functionは除外 console.log(`${prop} = ${this[prop]}\n`); } } }; //引数をフルで指定 var cutomer1 = new Customer('0001', '太郎'); cutomer1.printInfo(); //【表示結果】 //customerId = 0001 //name = 太郎 //customerIdのみ指定 var cutomer2 = new Customer('0002'); cutomer2.printInfo(); //【表示結果】 //customerId = 0002 //name = default |
タグ :
JavaScript