Js constructor pattern

From Intense-Visions/harness-engineering · View interactive version

Js constructor pattern is an AI agent skill from the GitHub repository Intense-Visions/harness-engineering. > Use constructor functions or ES6 classes to create and initialize objects

How to use this skill

Skill file

JS Constructor Pattern

Use constructor functions or ES6 classes to create and initialize objects

When to Use

Instructions

  1. Use ES6 class syntax over function constructors for readability.
  2. Put per-instance data in the constructor (this.x = ...).
  3. Put shared methods on the class body (they go on the prototype automatically).
  4. Use private class fields (#field) for data that should not be accessible externally.
class Rectangle {
  #area = null;

  constructor(width, height) {
    if (width <= 0 || height <= 0) throw new RangeError('Dimensions must be positive');
    this.width = width;
    this.height = height;
  }

  getArea() {
    if (this.#area === null) {
      this.#area = this.width * this.height; // memoize
    }
    return this.#area;
  }

  toString() {
    return `Rectangle(${this.width}x${this.height})`;
  }
}

const r = new Rectangle(4, 5);
console.log(r.getArea()); // 20
console.log(r instanceof Rectangle); // true

Details

The Constructor pattern is the foundation of object-oriented JavaScript. ES6 classes are syntactic sugar over prototype-based inheritance — class bodies define methods on ClassName.prototype, exactly like the older function Constructor() {} approach.

Trade-offs:

When NOT to use:

Source

https://patterns.dev/javascript/constructor-pattern

Process

  1. Read the instructions and examples in this document.
  2. Apply the patterns to your implementation, adapting to your specific context.
  3. Verify your implementation against the details and edge cases listed above.

Harness Integration

Success Criteria

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.