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