[英]Extending Object.prototype breaks JavaScript for..in loops, which are used heavily in Google Maps API v3
我正在開發流星項目。 我需要找到對象鍵表單對象值。 所以我嘗試了下面的代碼,但瀏覽器凍結了。
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'
控制台日志
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
控制台消息說這一切都沒有。 你可能會通過這樣做並在循環機制中打破tte來引發一個infinte循環。
擴展原生對象原型幾乎總是一個壞主意。
如果您想要數據對象,只需創建一個數據對象來存儲數據
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.