「JavaScript/クラス」の版間の差分

削除された内容 追加された内容
Ef3 (トーク | 投稿記録)
→‎ユーザー定義クラスのインスタンス配列: ユーザー定義クラスのインスタンスを配列化する為には、コンストラクターのパラメータをコレクションにしたものを、イテレーションし Array::map() でコンストラクターに渡すと簡素に表現できます。
タグ: 2017年版ソースエディター
Ef3 (トーク | 投稿記録)
→‎包含と継承: クラスのフィールドを明示的に定義
タグ: 2017年版ソースエディター
116 行
クラス間の関係で混乱しやすいのが、包含と継承です。
;包含:クラスAがクラスBを1つまたは複数プロパティに持っている。⇒ クラスAはクラスBを包含している。
;継承:クラスAのプロパティPを参照したとき、A.Pが定義されていなかっければクラスBのプロパティPが参照される。⇒ クラスAはクラスBを継承している。
;[https://paiza.io/projects/kCwHt4KotfPoZxngBCx0cwT3soCyAl2q2QmbsVXHykpA?language=javascript 包含と継承のサンプルコード]:<syntaxhighlight lang="javascript" highlight='1620,2730,34' line>
class Point {
x
constructor(x = 0, y = 0) {
y
console.info("Point::constructor")
return Object.assignconstructor(this,x {= x0, y }= 0); {
console.info("Point::constructor")
}
move(dxthis.x = 0, dy = 0) {x
this.xy += dxy
}
this.y += dy
constructormove(xdx = 0, ydy = 0) {
console.info('Point::move');
this.x += return thisdx
}this.y += dy
console.info('Point::move');
return this
}
}
 
class Shape {
location
constructor(x = 0, y = 0) {
constructor(x = 0, y = 0) {
this.location = new Point(x, y)
console.info("Shape::constructor")
}
return this
move(x, y) }{
this.location.move(x, y) {
this.locationconsole.info('Shape::move(x, y')
return this
console.info('Shape::move');
}
return this
}
}
 
class Rectangle extends Shape {
width
height
constructor(x = 0, y = 0, width = 0, height = 0) {
super(x, y)
Objectthis.assign(this,width {= width, height })
this.height = height
console.info("Rectangle::constructor")
}
return this
}
}
 
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='34' line>
class Shape {
location
constructor(x = 0, y = 0) {
this.location = new Point(x, y)
</syntaxhighlight>
:ShapeはPointを包含している。
;継承関係:<syntaxhighlight lang="javascript" start=27 highlight='1,35' line>
class Rectangle extends Shape {
width
height
constructor(x = 0, y = 0, width = 0, height = 0) {
super(x, y)