如何修改原型上的getter/setter方法?

3

对于原型上的函数,我过去会这样做:

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”。
我不确定该怎么做,如何修改原型上的getter/setter?

这可能会有帮助:https://dev59.com/XWkw5IYBdhLWcg3wu9Jh - luek baja
@luekbaja 同样的错误,但情况不同。 - iMrDJAi
1个回答

2

您不想从原型中调用 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>


1
太好了,Object.getOwnPropertyDescriptor 就是我要找的! - iMrDJAi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接