[Solved] How to use “String.prototype” in javascript


If you were going to augment a built-in prototype to do this, it would make more sense to augment Element.prototype, not String.prototype, since what you’re trying to use hide on isn’t a string, it’s an HTMLElement instance (which inherits from Element).

But it’s usually not a good idea to augment/extend the built-in prototypes. It’s fragile. If two scripts in the same page do it using the same name, they interfere with each other. If the DOM later gets a hide method, that messes up your existing code. Etc. Better to have a function you pass the element into:

function hide(element) {
    element.style.display = "none";
}

setTimeout(() => {
    hide(document.getElementById("id"));
}, 800);
<h1 id="id">Hi there</h1>

But if you do do it, make the extension non-enumerable by using defineProperty:

Object.defineProperty(Element.prototype, "hide", {
    value() {
        this.style.display = "none";
    },
    writable: true,
    configurable: true,
    enumerable: false, // This is the default, but I'm including it for emphasis...
});

setTimeout(() => {
    document.getElementById("id").hide();
}, 800);
<h1 id="id">Hi there</h1>

If you really, really wanted to, you could do this on String.prototype by assuming the string is the id of an element (or a selector for an element). For instance:

Object.defineProperty(String.prototype, "hide", {
    value() {
        const element = document.getElementById(this);
        if (element) {
            element.style.display = "none";
        }
    },
    writable: true,
    configurable: true,
    enumerable: false, // This is the default, but I'm including it for emphasis...
});

setTimeout(() => {
    "id".hide();
}, 800);
<h1 id="id">Hi there</h1>

But I wouldn’t do that. 🙂

solved How to use “String.prototype” in javascript