Skip to content

Instantly share code, notes, and snippets.

@itsMapleLeaf
Created December 3, 2016 00:49
Show Gist options
  • Save itsMapleLeaf/9d71f26cbf7dc21f80a422efa5aa4ddd to your computer and use it in GitHub Desktop.
Save itsMapleLeaf/9d71f26cbf7dc21f80a422efa5aa4ddd to your computer and use it in GitHub Desktop.
Inheritance vs Composition/Delegation
class Rect {
constructor(x, y, w, h) {
this.x = x
this.y = y
this.w = w
this.h = h
}
move(dx, dy) {
// ...
}
}
class Physics {
constructor() {
this.xvel = 0
this.yvel = 0
}
updatePosition(rect, elapsed) {
rect.x += this.xvel * elapsed
rect.y += this.yvel * elapsed
}
resolveCollision(rect, other) {
// ...
}
}
class Player {
constructor(x, y) {
this.rect = new Rect(x, y, 50, 50)
this.physics = new Physics()
}
update(elapsed) {
this.physics.update(this.rect, elapsed)
}
draw(canvas) {
this.rect.draw()
}
}
class Rect {
constructor(x, y, w, h) {
this.x = x
this.y = y
this.w = w
this.h = h
}
move(dx, dy) {
// ...
}
draw(canvas) {
// ...
}
}
class PhysicsObject extends Rect {
constructor(x, y, w, h) {
super(x, y, w, h)
this.xvel = 0
this.yvel = 0
}
updatePosition(elapsed) {
this.x += this.xvel * elapsed
this.y += this.yvel * elapsed
}
resolveCollision(other) {
// ...
}
}
class Player extends PhysicsObject {
constructor(x, y) {
super(x, y, 50, 50)
}
update(elapsed) {
this.updatePosition(elapsed)
}
draw(canvas) {
this.draw(canvas)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment