JavaScriptで多重継承もどき
コンストラクタ関数内で継承したいクラスのコンストラクタ関数を下記のように実行すると"多重継承のようなもの"ができるようです。
参考 : No Multiple Inheritance - MDC
//継承元1 function SuperClass1(prop1) { this.prop1 = prop1; }; //継承元2 function SuperClass2(prop2) { this.prop2 = prop2; }; //子クラス function SubClass(prop1, prop2, prop3) { //多重継承 this.superClass1 = SuperClass1; this.superClass1(prop1); this.superClass2 = SuperClass2; this.superClass2(prop2); this.prop3 = prop3; }; var subClass = new SubClass("a", "b", "c"); console.log( subClass.prop1 ); // a console.log( subClass.prop2 ); // b console.log( subClass.prop3 ); // c
通常の継承
// 親クラスコンストラクタ /** * 商品オブジェクトを作成 * @param {string} name 商品名 * @param {number} price 値段 * @constructor */ function Product(name,price) { this.name = name || "無題"; this.price = price || 0; }; /** * 名前を表示 */ Product.prototype.displayName = function() { alert(this.name); }; //子クラスコンストラクタ /** * 本オブジェクトを作成 * @param {string} name 商品名 * @param {number} price 値段 * @param {string} author 著者名 * @constructor * @extends {Product} */ function Book(name, price, author) { //親クラスのコンストラクタを実行 this.constructor(name, price); this.author = author; }; //Productクラスを継承 Book.prototype = new Product; /** * 名前を表示する * @override */ Book.prototype.displayName = function() { console.log(this.name); //オーバーライド元のメソッドを呼び出す方法1 this.superDisplayName= Product.prototype.displayName; this.superDisplayName(); //オーバーライド元のメソッドを呼び出す方法2 Product.prototype.displayName.apply(this, []); }; var book1 = new Book("我が輩は猫である", 800, "夏目漱石"); book1.displayName();
多重継承もどき(インターフェースもどき)
//親クラスコンストラクタ /** * 商品オブジェクトを作成 * @param {string} name 商品名 * @param {number} price 値段 * @constructor */ function Product(name,price) { this.name = name || "無題"; this.price = price || 0; }; /** * 名前を表示 */ Product.prototype.displayName = function() { alert(this.name); }; //インターフェースコンストラクタ /** * @interface */ function IMedia(mediaType) { this.mediaType = mediaType; }; /** * メディアタイプを返す * @return {string} */ IMedia.prototype.getMediaType = function() {}; //子クラスコンストラクタ /** * 書籍オブジェクトを作成 * @param {string} name 商品名 * @param {number} price 値段 * @param {string} author 著者名 * @constructor * @extends {Product} * @implements {IMedia} */ function Book(name, price, author) { //親クラスのコンストラクタを実行 this.constructor(name, price); //IMediaを多重継承 this.media = IMedia; this.media("paper"); this.author = author; }; //Productクラスを継承 Book.prototype = new Product; /** * 名前を表示する * @override */ Book.prototype.displayName = function() { console.log(this.name); //オーバーライド元のメソッドを呼び出す方法1 this.superDisplayName= Product.prototype.displayName; this.superDisplayName(); //オーバーライド元のメソッドを呼び出す方法2 Product.prototype.displayName.apply(this, []); }; //メソッドは継承されないので子クラスで実装 /** * メディアタイプを返す * @return {string} */ Book.prototype.getMediaType = function() { return this.mediaType; }; var book1 = new Book("我が輩は猫である", 800, "夏目漱石"); book1.displayName(); console.log( book1.getMediaType() );