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

Use Symbol to get a secure separation #3358

Open
ceving opened this issue Feb 7, 2023 · 0 comments
Open

Use Symbol to get a secure separation #3358

ceving opened this issue Feb 7, 2023 · 0 comments

Comments

@ceving
Copy link

ceving commented Feb 7, 2023

This affects: https://javascript.info/mixins

The example uses a wired underline hack to separate the storage used by the condiment object being mixed into the mixture object.

Things get more secure and much simpler, if you think about the condiment as a function returning the object to mix in. Then you can use Symbol to generate a unique identifier, which can be used by the condiment to access its own storage.

function mixin(mixture, condiment) {
  let self = Symbol('self')
  mixture[self] = {}
  Object.assign(mixture, condiment(self))
}

function events(self) {
  return {
    on(event, react) {
      this[self][event] = react
    },
    off(event) {
      delete this[self][event]
    },
    trigger(event, ...args) {
      this[self][event](...args)
    }
  }
}

class Menu {
  choose(value) {
    this.trigger("select", value)
  }
}

mixin(Menu.prototype, events)

var menu = new Menu()

menu.on("select", value => console.log("selected:", value))
menu.choose("123")

Also, if you use already the ellipsis syntax, you can use it in both cases instead of apply.

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