Class Syntax vs Constructor Function
Two ways to define objects, and the trade-offs between them.
AnimatedObject Class
A reusable class for canvas-based animations.
class AnimatedObject {
constructor(x, y, size = 10, color) {
this.x = x;
this.y = y;
this.size = size;
this.color = color;
this.velocity = 1;
}
update() {
this.x += this.velocity;
this.y += this.velocity;
this.size = 10 + 5 * Math.sin(Date.now() / 1000); // pulse
}
draw(ctx) {
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
ctx.fill();
}
}
Player: Constructor Function Style
An alternative way to define objects using functions.
function Player(x, y, size, color, ctx) {
this.x = x;
this.y = y;
this.size = size;
this.color = color;
this.velocity = 1;
this.ctx = ctx;
this.update = function () {
this.x += this.velocity;
this.y += this.velocity;
};
this.draw = function () {
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
ctx.fill();
};
}
Class vs Constructor Function
| Feature | class | function |
|---|---|---|
| Syntax | Cleaner | Verbose |
| Methods on | Prototype | Each instance |
| Memory | Efficient | Less efficient |
| Inheritance | extends | Prototype chain |
| Readability | Higher | Lower |
Understanding the trade-offs
| class syntax — recommended | Constructor function — legacy |
|---|---|
|
Methods defined once on the prototype, shared by all instances Supports static methods, getters and setters natively Uses extends for clean inheritanceClass bodies run in strict mode automatically More readable, closer to Java/C++ |
Methods are re-created for every new instance (more memory) Familiar to developers used to older JavaScript patterns Inheritance requires manual prototype chaining Works in older environments without transpiling Flexible: can return different object types |
Activity — complete the code
Complete the code correctly to mark this lesson as complete automatically.
Compare class syntax with the constructor function style.
// Class syntax: methods live on theclass Player {constructor(x, y) { this.x = x; this.y = y; }update() { this.x += 1; }}// Constructor function: methods are re-created for everyfunction Enemy(x, y) {this.x = x;this.y = y;this.update = () { this.x += 1; };}// Inheritanceclass Boss Player {}