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

It already can somewhat be done with decorators and private fields #8

Closed
augustobmoura opened this issue Aug 9, 2019 · 0 comments
Closed

Comments

@augustobmoura
Copy link

augustobmoura commented Aug 9, 2019

Some decorator can modify a class method to require a "secret" first argument before calling the host method

const safe = secret => fn => function (passedSecret, ...args) {
  if (passedSecret !== secret) {
    throw Error('Wrong password sir');
  }
  return fn.apply(this, args);
};


const secret = Symbol();

class Foo {
  #bar;
  getBar() {
    return this.#bar;
  }
}

// Current way of decoration
Foo.prototype.getBar = safe(secret)(Foo.prototype.getBar);

const foo = new Foo();
foo.getBar(); // Error
foo.getBar(anyOtherSymbol) // Also error
foo.getBar(secret) // Voilà

In the future we can also use the new decorator syntax

class Bar {
  @safe(secret)
  setBar(newValue) {
    // ...
  }
}

One problem is that it adds the complexity to having to call the method with another argument

The other problem is that it looses the static analyzable property of the current syntax. In my opinion Javascript per se don't need this kind of static analyzable syntax (not yet at least), we already have a lot of static typed languages that do a pretty good job at preventing typos and restricting member permissions, it would be a lot more fitting if this languages implemented some type of module scoped access (in fact there's already ongoing discussions about the subject)

Anyway, I think this proposal is in the right direction, keep up with the good work!

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

No branches or pull requests

1 participant