What does MooTools' Function.prototype.overloadSetter() do?

Viewed 1302

I'm looking through the MooTools source to try and understand its .implement() and .extend() utilities.

The definition of each refers to a function defined like this:

var enumerables = true;
for (var i in {toString: 1}) enumerables = null;
if (enumerables) enumerables = ['hasOwnProperty', 'valueOf', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'constructor'];

Function.prototype.overloadSetter = function(usePlural){
    var self = this;
    return function(a, b){
        if (a == null) return this;
        if (usePlural || typeof a != 'string'){
            for (var k in a) self.call(this, k, a[k]);
            if (enumerables) for (var i = enumerables.length; i--;){
                k = enumerables[i];
                if (a.hasOwnProperty(k)) self.call(this, k, a[k]);
            }
        } else {
            self.call(this, a, b);
        }
        return this;
    };
};

However, I am having a tough time understanding what it does.

Can you explain how this function works and what it does?

2 Answers

The part that had me scratching my head for a while was the

var enumerables = true; for (var i in {toString: 1}) enumerables = null;

part, which turns out to be a test for the DontEnum bug that some browsers have. At first glance it seems like it should just set enumerables to null, but with the DontEnum bug toString is suppressed (wrongly, because the object's prototype.toString has the DontEnum flag) and enumerables is left as true.

overloadSetter (or rather the resulting function) then has to check one at a time for the seven properties that the DontEnum bug affects, to see if they exist in the object argument.

Related