JavaScript: Mastering Prototype

From The Travis van der Font Wiki
Jump to: navigation, search
const masterIcon = document.querySelector('#id');

Simple object method

masterIcon.updateClass(glyphicon.right, glyphicon.down);

HTMLElement.prototype.updateClass = function (originalClass, newClass)
{
    if (this.className === originalClass)
    {
        this.className = newClass;
    }
    else
    {
        this.className = originalClass;
    }
};

Extensive object method

masterIcon.UI.updateClass(glyphicon.right, glyphicon.down);

Object.defineProperty(Element.prototype, 'UI', {
    get: function ()
    {
        return {
            element: this,
            updateClass: function (originalClass, newClass)
            {
                if (this.className === originalClass)
                {
                    this.className = newClass;
                }
                else
                {
                    this.className = originalClass;
                }
            },
        }
    },
    configurable: true,
    writeable:    false
});