javascript-tutorial / javascript-tutorial/en.javascript.info
Use Symbol to get a secure separation
还没有人认领这个 Issue。
- 主要语言
- HTML
- 星标
- 25.5k
- 派生
- 4k
- PR 合并指标
- 30 天内没有已合并 PR
描述
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.
贡献指南
这个仓库没有索引到贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
打开 https://javascript.info/mixins 上的 mixins 文章,找到使用基于下划线的存储分隔符的示例。将其与提议的基于 Symbol 的示例以及省略号语法建议进行比较;当文章反映所要求的改进时即表示完成。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- javascript
- 领域
- documentation
- Issue 类型
- 文档
- 难度
- 2/5
- 预计耗时
- 1-3 小时
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 55/100