【JavaScript】継承(プロトタイプチェーン)のサンプル
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 37 38 39 40 41 42 43 44 |
//=====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`); } } }; //=====PrimeCustomerオブジェクトの定義===== //コンストラクターの定義 var PrimeCustomer = function(customerId, name, primeRank = 'default') { Customer.call(this, customerId, name); this.primeRank = primeRank; } //基底クラス(Customer)のプロパティを継承 PrimeCustomer.prototype = new Customer(); //プロパティの追加 PrimeCustomer.prototype.getPrimeRank = function() { return this.primeRank; }; //=====オブジェクトをインスタンス化===== var pCutomer1 = new PrimeCustomer('0001', '太郎', 'Royal'); pCutomer1.printInfo(); //【表示結果】 //customerId = 0001 //name = 太郎 //primeRank = Royal |
タグ :
JavaScript