Skip to content

Use Symbol to get a secure separation #3358

@ceving

Description

@ceving

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions