Search code examples
javascriptjqueryobjecthtml-object

jquery don´t accept property, cause given string and not object


description:

i try to get dynamically the values of HTML-Object´s. so i´ve written a prototype function select on Object. It works over the console, but not in the script. A jquery property has something against it.

the error:

Uncaught TypeError: can't assign to property "guid" on "innerText": not an object

output of the related object:

Object { 0: th, 1: th, 2: th, 3: th, 4: th, 5: th, length: 6, prevObject: {…} }

function select on Object:

Object.prototype.select = function(what)
{
    return this.map(function() {
        return this[what];
    }).get();
}

the call:

label.select('innerText')

is it a known bug? is there a workaround? The debugger is just relating to a point in jquery:

S.find.matchesSelector(re,i),n.guid||(n.guid=S.guid++)

made already a workaround:

function getData(data)
{
    return $(data).map(function() {
        return this.value;
    }).get();
}

Solution

  • It's never a good idea to add properties to the Object.prototype object. And it's an especially bad idea to add them with simple assignment like that so that they're enumerable. Also, looking at the content of your select function, note that virtually no objects have a map method on them. (Arrays are the only built-in object with map. jQuery objects also have it.)

    I strongly recommend not adding anything to Object.prototype.

    But if you do it anyway, make what you add *non-enumerable`:

    Object.defineProperty(Object.prototype, "select", {
        value() {
            // ...your code here
        },
        writable: true,
        configurable: true,
    });
    

    That's still not a good idea, because it's not uncommon for libraries to have their own specialized objects, which may well have a select method (jQuery objects do, for instance), setting you up for conflicts. But at least if you make it non-enumerable, the property won't show up in for-in loops and similar.