ES6継承メモ
使い方
・ ES5
function Book(options) { this.title = options.title; this.ReadFlag = false; } Book.prototype.isRead = function () { return this.ReadFlag; } function Takashi(options) { Book.call(this, options);//Bookを継承 this.price = options.price; } Takashi.prototype = Object.create(Book.prototype);//Bookのメソッドをコピー Takashi.prototype.constructor = Takashi; Takashi.prototype.FinishedReading = function(){ this.ReadFlag=true; } let takashi = new Takashi({ title: '火ノ丸相撲', price: 500 }); takashi.FinishedReading(); takashi.isRead(); takashi;
出力結果 True {"title":"火ノ丸相撲","ReadFlag":true,"price":500}
・ ES6
class Book { constructor(options){ this.title = options.title; this.ReadFlag = false; } //メソッド isRead(){ return this.ReadFlag; } } class Takashi extends Book { constructor(options){ super(options);//親のコンストラクタを呼んでいる(引数がある場合は引数も渡す) this.price = options.price; } FinishedReading(){ this.ReadFlag = true; } } const takashi = new Takashi({ title: '火ノ丸相撲', price: 500 }); takashi.FinishedReading(); takashi.isRead(); takashi;
出力結果 True {"title":"火ノ丸相撲","ReadFlag":true,"price":500}
継承の使い所さん
ライブラリのClassを継承して使ったり
後は自分が汎用的なClassを作った後そのClassを別でも使う的な用途
例
例:ゲーム
この例では、モンスターの基礎ステータスをMonsterクラスに格納し、
Snakeクラスで継承damageメソッドが呼ばれた時にSnakeインスタンスの
モンスターにダメージが入るというプログラム
ここで注意が必要なのはdamageメソッドの引数にEnemyインスタンスを
入れないと別のモンスターにもダメージが入る可能性があるので
引数に指定しているという点
class Monster { constructor(options){ this.name = options.name; this.health = 100; } } class Snake extends Monster{ constructor(options){ super(options); } damage(targetMonster){ if(targetMonster.health - 10 < 0){ targetMonster.health = 0; } else targetMonster.health = targetMonster.health - 10; return targetMonster.health; } } let Enemy = new Snake({name:"蛇だよ"}); Enemy Enemy.damage(Enemy); Enemy
出力結果 {"name":"蛇だよ","health":100} 90 {"name":"蛇だよ","health":90}