「JavaScript/クラス」の版間の差分
削除された内容 追加された内容
→ユーザー定義クラスのインスタンス配列: ユーザー定義クラスのインスタンスを配列化する為には、コンストラクターのパラメータをコレクションにしたものを、イテレーションし Array::map() でコンストラクターに渡すと簡素に表現できます。 タグ: 2017年版ソースエディター |
→包含と継承: クラスのフィールドを明示的に定義 タグ: 2017年版ソースエディター |
||
116 行
クラス間の関係で混乱しやすいのが、包含と継承です。
;包含:クラスAがクラスBを1つまたは複数プロパティに持っている。⇒ クラスAはクラスBを包含している。
;継承:クラスAのプロパティPを参照したとき、A.Pが定義されていな
;[https://paiza.io/projects/
class Point {
x
constructor(x = 0, y = 0) {▼
y
console.info("Point::constructor")▼
}▼
console.info('Point::move');▼
this.x +=
}
class Shape {
location
constructor(x = 0, y = 0) {
this.location = new Point(x, y) ▲ return this
move(x, y)
this.location.move(x, y)
}
▲ return this
▲ }
}
class Rectangle extends Shape {
width
height constructor(x = 0, y = 0, width = 0, height = 0) { this.height = height
console.info("Rectangle::constructor") }
▲ }
}
161 ⟶ 166行目:
rct.move(11, 21)
console.info("rct = ", rct)
let rct2 = new Rectangle(1, 2, 10, 150)
console.info("rct = ", rct)
console.info("rct2 = ", rct2)
</syntaxhighlight>
;実行結果:<syntaxhighlight lang="javascript" line>
174 ⟶ 182行目:
Shape::move
rct = Rectangle { location: Point { x: 23, y: 53 }, width: 100, height: 50 }
Point::constructor
Shape::constructor
Rectangle::constructor
rct = Rectangle { location: Point { x: 23, y: 53 }, width: 100, height: 50 }
rct2 = Rectangle { location: Point { x: 1, y: 2 }, width: 10, height: 150 }
</syntaxhighlight>
;包含関係:<syntaxhighlight lang="javascript" start=14 highlight='
class Shape {
location
constructor(x = 0, y = 0) {
this.location = new Point(x, y)
</syntaxhighlight>
:ShapeはPointを包含している。
;継承関係:<syntaxhighlight lang="javascript" start=27 highlight='1,
class Rectangle extends Shape {
width
height
constructor(x = 0, y = 0, width = 0, height = 0) {
super(x, y)
|