2 回答

TA貢獻1820條經驗 獲得超10個贊
這里的主要問題是您直接返回querySelectororquerySelectorAll結果。您可以將其包裝在您自己的類中,您可以使用方法輕松擴展該類。
class ElementsHelper {
constructor(elements) {
this.elements = elements;
}
// helper to simplify iterating `this.elements` and returning `this`
forEach(fn) {
this.elements.forEach(fn);
return this;
}
hide() {
return this.forEach(element => element.style.display = "none");
}
click(fn) {
return this.forEach(element => element.addEventListener("click", fn));
}
}
function $(selector) {
return new ElementsHelper(document.querySelectorAll(selector));
}
通過上述操作,您現在可以執行以下操作:
$('#myDiv').hide();

TA貢獻1886條經驗 獲得超2個贊
你基本上有兩個選擇:
像 jQuery 一樣使用你自己的對象,或者
擴展內置原型。
返回每個單獨的結果對象時對其進行擴展
我可能會使用方法#1,也許是擴展Array
(或通過組合使用數組)。
你似乎更喜歡方法#2。通常不建議這樣做,因為一旦開始組合來自多個位置的腳本,就會遇到潛在的沖突。但在應用程序(而不是庫)內,這不一定不合理。
在您的情況下,如果您的$
函數返回 的結果querySelectorAll
,它將返回 a?NodeList
,并且您可以擴展NodeList.prototype
。每當擴展原型時,始終使用Object.defineProperty
(或類似的)來定義不可枚舉的屬性。例如:
Object.defineProperty(NodeList.prototype, "hide", {
? ? value() {
? ? ? ? this.forEach(/*...*/);
? ? ? ? return this;
? ? },
? ? writable: true,
? ? configurable: true
});
實例:
Object.defineProperty(NodeList.prototype, "hide", {
? ? value() {
? ? ? ? // This isn't a great "hide", it's just for
? ? ? ? // the purposes of showing the plumbing
? ? ? ? this.forEach(el => el.style.display = "none");
? ? ? ? return this;
? ? },
? ? writable: true,
? ? configurable: true
});
const $ = selector => document.querySelectorAll(selector);
setTimeout(() => {
? ? $(".a").hide();
? ? console.log("Hid .a elements");
}, 800);
<div class="a">a</div>
<div class="b">b</div>
<div class="c">c</div>
不幸的是,
__proto__
現在已被棄用
這是真的,但Object.getPrototypeOf
不是,只是__proto__
訪問器屬性(它只是為了向后兼容而添加到規范中)。
添加回答
舉報