javascript-tutorial / javascript-tutorial/en.javascript.info
Use Symbol to get a secure separation
Nobody has claimed this yet.
- Dominant language
- HTML
- Stars
- 25.5k
- Forks
- 4k
- PR merge metrics
- No merged PRs in 30d
Description
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.
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Open the mixins article at https://javascript.info/mixins and locate the example using an underline-based storage separator. Compare it with the proposed Symbol-based example and the ellipsis-syntax suggestion; done means the article reflects the requested improvements.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 55/100