Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Late constructor assignments #14

Open
caspervonb opened this issue Nov 10, 2016 · 0 comments
Open

Late constructor assignments #14

caspervonb opened this issue Nov 10, 2016 · 0 comments
Labels

Comments

@caspervonb
Copy link
Contributor

caspervonb commented Nov 10, 2016

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant