for(var item in items)

by Ivan Gerasimenko

JavaScript

var log = function(msg) { console.log(msg); };

var obj1 = {a: 1, b: 2, c: 3};

/* // all objects have this method, but it's polluted with itself 'allKeys'
 // be careful when creating dictionaries
Object.prototype.allKeys = function() {
    var result = [];
    for (var key in this) {
        result.push(key);
    }
    return result.join(', ');
}

log( obj1.allKeys() ); // return: 'a, b, c, allKeys' */
// ^ could be rewritten with 'defineProperty' to avoid method 'allKeys' in properties
// USE 'definePrototype' to add not-enumerable properties to Object
// not-enumerable - not seen by for...in...
Object.defineProperty(Object.prototype, 'allKeys', {
    value: function () {
        var result = [];
        for (var key in this) {
            result.push(key);
        }
        return result.join(', ');
    },
    writable: true,
    enumerable: false,    // makes property hidden for for..in !!!
    configurable: true
});

log('Properties list by method:');
log( obj1.allKeys() );


function allKeys(obj) {
    var result = [];
    for (var key in obj) {
        result.push(key);
    }
    return result.join(', ');
}

log('Properties list by function:');
log( allKeys(obj1) );