Rewrite `Function.prototype.method = ` ⇒ es6 class

JavaScript pattern

Older code often uses the function prototype to create "classes" out of functions. This upgrades those to ES6 class syntax.


Apply with the Grit CLI
grit apply proto_to_class

Transforms constructor and methods

BEFORE
function MyClass() {
  this.field = 1;
}

MyClass.prototype.update = function () {
  this.field += 1;
};
AFTER
class MyClass {
  constructor() {
    this.field = 1;
  }

  update() {
    this.field += 1;
  }
}

Transforms and ignores empty constructor

BEFORE
function MyClass() {}

MyClass.prototype.update = function () {
  this.field += 1;
};
AFTER
class MyClass {
  update() {
    this.field += 1;
  }
}

Transforms persisting constructor arguments

BEFORE
function MyClass(arg1) {
  someCall();
  this.field = arg1;
}

MyClass.prototype.update = function () {
  this.field += 1;
};
AFTER
class MyClass {
  constructor(arg1) {
    someCall();
    this.field = arg1;
  }

  update() {
    this.field += 1;
  }
}

Does not transform non-prototype edited functions

JAVASCRIPT
function MyFunction() {
  return '';
}