Quantcast
Channel: javascript – frag (frăg)
Viewing all articles
Browse latest Browse all 37

Hiding enumerables after MooTools changes prototypes

$
0
0

One of the most common complaints of people when using 3-rd party code that breaks on MooTools pages is when somebody incorrectly tries to iterate through an Array with the for (var in) operator and the methods and properties added by the framework also show up. When you cannot change the code to add hasOwnProperty, it leaves you with very little options. Or… you could fix things.

var foo = ['one','two'],
    key;

for (key in foo){
    // lists all mootools methods and properties as well as 0, 1
    console.log(key, foo[key]); // needs hasOwnProperty etc, ppl complain.
}

// protect enumerables under ES5 in Array
(function(){
    // set mootools expandos to non-enumerables under ES5
    var key,
        a = [];
    
    for (key in a) a.hasOwnProperty(key) || Object.defineProperty(Array.prototype, key, {
        enumerable:false
    });
}());

console.info('trying again...');

for (key in foo){
    console.log(key, foo[key]);    
}

See this in action on jsfiddle.

An alternative approach may be available by patching MooTools core. You need to mod the implement function in Core.js here: https://github.com/mootools/mootools-core/blob/master/Source/Core/Core.js#L192-L209 and adding something like:

if (previous == null || !previous.$protected) this.prototype[name] = method;
Object.defineProperty && Object.defineProperty(this, name, { enumerable: false });

Viewing all articles
Browse latest Browse all 37

Trending Articles