如何修改原型上的getters/setters?
How to modify getters/setters on prototypes?
对于原型上的函数,我曾经做过类似的事情:
var attachShadow = HTMLElement.prototype.attachShadow
HTMLElement.prototype.attachShadow = function (option) {
var sh = attachShadow.call(this, option)
console.log('ShadowDOM Attached!')
return sh
}
在这个例子中,我修改了 HTMLElement
原型中的 attachShadow
方法,以便在新的 shadowDOM
附加到元素时通知我。
现在我想对ShadowRoot.prototype.adoptedStyleSheets
做一些类似的事情,但是这次adoptedStyleSheets
是一个getter/setter,var adoptedStyleSheets = HTMLElement.prototype.adoptedStyleSheets
会导致错误:Uncaught TypeError: Illegal invocation
。
我不知道该怎么做,如何修改 getters/setters 原型?
您不想检索 adoptedStyleSheets
中的值(从原型调用时显然会抛出错误)但它的 属性 描述符是为了在您自己的 adoptedStyleSheets
:
(function () {
const oldAdoptedStyleSheetsGetter = Object.getOwnPropertyDescriptor(ShadowRoot.prototype, 'adoptedStyleSheets');
Object.defineProperty(ShadowRoot.prototype, "adoptedStyleSheets", {
get: function () {
console.log('adoptedStyleSheets was accessed!');
return oldAdoptedStyleSheetsGetter.get.call(this)
},
});
})();
customElements.define('web-component', class extends HTMLElement {
connectedCallback() {
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `Hi I'm a web component`;
console.log('this.shadowRoot.adoptedStyleSheets:', this.shadowRoot.adoptedStyleSheets);
}
});
<web-component></web-component>
对于原型上的函数,我曾经做过类似的事情:
var attachShadow = HTMLElement.prototype.attachShadow
HTMLElement.prototype.attachShadow = function (option) {
var sh = attachShadow.call(this, option)
console.log('ShadowDOM Attached!')
return sh
}
在这个例子中,我修改了 HTMLElement
原型中的 attachShadow
方法,以便在新的 shadowDOM
附加到元素时通知我。
现在我想对ShadowRoot.prototype.adoptedStyleSheets
做一些类似的事情,但是这次adoptedStyleSheets
是一个getter/setter,var adoptedStyleSheets = HTMLElement.prototype.adoptedStyleSheets
会导致错误:Uncaught TypeError: Illegal invocation
。
我不知道该怎么做,如何修改 getters/setters 原型?
您不想检索 adoptedStyleSheets
中的值(从原型调用时显然会抛出错误)但它的 属性 描述符是为了在您自己的 adoptedStyleSheets
:
(function () {
const oldAdoptedStyleSheetsGetter = Object.getOwnPropertyDescriptor(ShadowRoot.prototype, 'adoptedStyleSheets');
Object.defineProperty(ShadowRoot.prototype, "adoptedStyleSheets", {
get: function () {
console.log('adoptedStyleSheets was accessed!');
return oldAdoptedStyleSheetsGetter.get.call(this)
},
});
})();
customElements.define('web-component', class extends HTMLElement {
connectedCallback() {
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `Hi I'm a web component`;
console.log('this.shadowRoot.adoptedStyleSheets:', this.shadowRoot.adoptedStyleSheets);
}
});
<web-component></web-component>