简体   繁体   中英

Extending Object.prototype breaks JavaScript for..in loops, which are used heavily in Google Maps API v3

I am developing project in meteor. I need to find object key form object value. So I tried the below code, But browser freezed.

Object.prototype.getKeyByValue = function( value ) {
    for( var prop in this ) {
        if( this.hasOwnProperty( prop ) ) {
             if( this[ prop ] === value )
                 return prop;
        }
    }
}

var test = {
   key1: 42,
   key2: 'foo'
};

test.getKeyByValue( 42 );  // returns 'key1'

console log

This site adds property <getKeyByValue> to Object.prototype. Extending Object.prototype breaks JavaScript for..in loops, which are used heavily in Google Maps API v3

The console message says it all doesn't it. You probaly caused an infinte loop by doing this and breaking tte for..in loop mechanics.

Extending native objects prototypes is almost always a bad idea.

If you want data objects just make a dataobject for storage of data

 function SimpleMap() { this.list = {}; } SimpleMap.prototype.getKeyByValue = function( value ) { for( var prop in this.list ) { if( this.list.hasOwnProperty( prop ) ) { if( this.list[ prop ] === value ) return prop; } } return null; } SimpleMap.prototype.size = function() { var count = 0; for( var prop in this.list ) { if( this.list.hasOwnProperty( prop ) ) { ++count; } } return count; } SimpleMap.prototype.isEmpty = function() { return this.size() === 0; } SimpleMap.prototype.empty = function() { this.list = {}; } SimpleMap.prototype.put = function(key, value) { this.list[key] = value; } SimpleMap.prototype.get = function(key) { return this.list[key]; } SimpleMap.prototype.remove = function(key) { delete this.list[key]; } var cars = new SimpleMap(); cars.put("volvo","vrooooom"); cars.put("citroen","frut frut frut"); cars.put("reliant","Darn you mr Bean"); var content = document.getElementById('frut'); content.appendChild(document.createTextNode("What does the reliant owner say? "+cars.get("reliant"))); content.appendChild(document.createElement('br')); content.appendChild(document.createTextNode("Who is vroooom? " + cars.getKeyByValue('vrooooom'))); content.appendChild(document.createElement('br')); content.appendChild(document.createTextNode("Is car storage empty? " + cars.isEmpty())); cars.empty() content.appendChild(document.createElement('br')); content.appendChild(document.createTextNode("Is the car storage empty now? " + cars.isEmpty())); 
 <div id="frut"> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM