【问题标题】:How to modify getters/setters on prototypes?如何修改原型上的 getter/setter?
【发布时间】:2020-09-22 15:44:35
【问题描述】:

对于原型上的函数,我曾经做过类似的事情:

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?

【问题讨论】:

标签: javascript prototype getter-setter


【解决方案1】:

您不想检索 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>

【讨论】:

  • 完美,所以Object.getOwnPropertyDescriptor 就是我要找的!
猜你喜欢
  • 1970-01-01
  • 2012-05-22
  • 1970-01-01
  • 1970-01-01
  • 2013-11-06
  • 1970-01-01
  • 2020-08-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多