Class method

2 snippets in JavaScript

JSJavaScript

Class Declaration

JS · Classes & OOP
syntax
class ClassName {
  constructor(params) { ... }
  method() { ... }
}
example
class Product {
  constructor(name, price) {
    this.name = name;
    this.price = price;
  }

  format() {
    return `${this.name}: $${this.price.toFixed(2)}`;
  }
}

const item = new Product("Notebook", 12.5);
console.log(item.format());
output
"Notebook: $12.50"

Note Classes are syntactic sugar over prototypes. They are NOT hoisted -- you must declare before use, unlike function declarations.

Static Methods and Properties

JS · Classes & OOP
syntax
class C {
  static method() { ... }
  static property = value;
}
example
class MathUtils {
  static PI = 3.14159265;

  static clamp(value, min, max) {
    return Math.min(Math.max(value, min), max);
  }

  static lerp(a, b, t) {
    return a + (b - a) * t;
  }
}

console.log(MathUtils.clamp(150, 0, 100)); // 100
console.log(MathUtils.lerp(0, 50, 0.5));  // 25

Note Static members belong to the class itself, not instances. Access them via ClassName.method(), not instance.method().