将原型继承到 JavaScript 中的所有子元素

inherit prototype to all child elements in JavaScript

本文关键字:元素 原型 继承 JavaScript      更新时间:2023-09-26

我想为每个 DOM 元素添加一些函数,但我不想遍历所有元素。这是一个演示代码:

window.onload = function () {
    /* get the constructor of document, which is Document
       add the clickMe function to the prototype */
    document.constructor.prototype.clickMe = function (func) {
        this.addEventListener('click', function () {
            func();
        });
    };
    document.clickMe(clickDocument); // works
    /* doesn't work, because the prototype of document.getElementById('random_btn')
       does not have the function clickMe (makes sense) */
    document.getElementById('random_btn').clickMe(clickRandomBtn);
}
function clickDocument() {
    alert("clicked documet");
}
function clickRandomBtn() {
    alert("clicked a random button");
}
如果我

理解你的问题,你想要这个:

Element.prototype.clickMe = function (func) {
    this.addEventListener('click', function () {
        func();
    });
};

示范

但是,更改本机对象的原型通常被视为一种不好的做法。请参阅可维护的 JavaScript:不要修改不属于您的对象