javascript - 将原型(prototype)继承给 JavaScript 中的所有子元素

标签 javascript function prototype inheritance

我想为每个 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();
    });
};

Demonstration

但更改原生对象的原型(prototype)通常被视为一种不好的做法。参见 Maintainable JavaScript: Don’t modify objects you don’t own

关于javascript - 将原型(prototype)继承给 JavaScript 中的所有子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19270933/

相关文章:

javascript - 在任何情况下我应该使用 in 运算符而不是 hasOwnProperty()?

javascript - 使用 RSpec 和 JS 选择元素

javascript - 缓存变量: localStorage or a cookie?

javascript - 无法在数组内填充数组 - Javascript

Java:自动 'throws'声明:是吗?如果是,它的值是多少?

javascript - js继承和原型(prototype)赋值

javascript - Bootstrap 下拉菜单: not close when click outside the menu

c# - Unity - Vector3 结构 - 通过引用传递值类型

javascript - div替换后如何调用Javascript?

javascript - 在 'this' 和对象的原型(prototype)方法中使用 'constructor' 时如何正确返回值?