Search code examples
javascriptsafaridefineproperty

Safari javascript error trying to define "remove" Element method


I have several definitions in my personal library, this one is generating error in Safari:

Object.defineProperty(Element.prototype, "remove", {
    enumerable: false,
    configurable: false,
    writable: false,
    value: function(){
        this.parentElement.removeChild(this);
    }
});

The error: TypeError: Attempting to change enumerable attribute of unconfigurable property.

I don't get what exactly this phrase means, in FireFox this error does not occurs.


Solution

  • The message says:

    1) Element.prototype has already the property remove.

    2) The configurable-attribute of this property is set to false. That means: the property remove is not changeable in any way.

    To evaluate that try:

    Object.getOwnPropertyDescriptor(Element.prototype, 'remove');
    

    Some browsers has no remove on Element.prototype, then your code works. Some browsers has, and configurable is set to true, then it works too and you overwrite the build-in-property.

    As an Aside: the attributes enumerable, configurable, and writable defaults to false, you must only declare them if wanting them to be true.

    A second Aside: It's not really a good idea to mess around in the build-in-prototypes.

    A last Aside: My Safari (5.1.7) hasn't Element.prototype.remove any more, and your code works.