我想用新方法擴展 vanilla DOM 對象,例如document.createElement()通過定義一個新方法來createElementWithAttrs()擴展,或者擴展Element但以下哪兩個是最佳實踐?方法A(就像Chrome DevTools 是如何做到的,但可能是因為代碼在 ES2015 之前很久就繼承自 WebKit)將新方法添加到現有 DOM 類原型中。// dom.jsDocument.prototype.createElementWithClass = (tagName, className) => { ... };Element.prototype.findEnclosingShadowRoot = () => { ... };// probably a few more// someScriptName.jsconst e1 = document.createElementWithClass(...);...const shadow = e2.findEnclosingShadowRoot();優點:簡潔直觀,因為它們可以像本地 DOM 的一部分一樣使用缺點:必須dom.js用<script>標簽插入HTML有時會讓讀者感到困惑(包括我自己,因為時間長了我可能會忘記)。方法B:在 ES 模塊中定義它們。// dom.jsexport const createElementWithClass = (tagName, className) => { ... };export const findEnclosingShadowRoot = (element) => { ... };// probably a few more// someScriptName.jsimport * as dom from './dom.js';const e1 = dom.createElementWithClass(...);...const shadow = dom.findEnclosingShadowRoot(e2);優點和缺點與上面的“缺點”和“優點”相反。有最佳實踐嗎?我是否錯過了一些需要考慮的優點/缺點?謝謝。
JavaScript:導入模塊或向“文檔”添加功能?
智慧大石
2021-12-23 14:47:24