hasharray / revaluate.js

non destructive code revaluation
https://revaluate.js.org
2 stars 0 forks source link

Late constructor assignments #14

Open caspervonb opened 8 years ago

caspervonb commented 8 years ago

Similar to late closure assignments in #1, constructor fields can get the same treatment!

The premise is simple

function Robot() {
}

var robot = new Robot();

That robot, has no data, if we were to edit

function Robot() {
  this.data = {};
}

Nothing would happen in normal execution, but that doesn't mean we cannot make something happen in this case.

Instance properties take precedence over prototype properties, knowing this simple fact we can actually introduce lazy initialisation.

Object.defineProperty(Robot.prototype, 'data', {
  get: {
    this.data = eval('{}');
    return this.data;
  },
});

It is however not without caveats one major consideration is dealing with parameters, e.g consider this:

class Robot {
  constructor(socket) {
    this.socket = socket;
  }
}

There is no way to "magic-initialize" things like that.