trying to override alert, it works, but executes twice

so, call me lazy but I'm trying to add a bit of syntactic sugar to Javascript's alert function. Here's the code:

<script src='jquery.js'></script>
window.nativeAlert = window.alert
window.alert = function() 
    window.nativeAlert(", ")+" window")
    return this
Array.prototype.alert = function()
    window.nativeAlert(this.toString()+" array")
    return this
Object.prototype.alert = function()
    window.nativeAlert(this.toString()+" object")
    return this
    var features = $.getJSON("features.json")

This seems to work, but is firing twice. Any idea why this happens? My gut says that it has something to do with overloading, but it works just fine (fires once) for arrays and for [window.]alert().

P.S. I know the JSON won't display properly yet, that's for later.



This was a tricky one, it took a little bit of stepping through the call stack in a debugger to see what was going on.

What's happening is that alert is being added as a property to every object. That includes the object that is deserialized from the features.json file.

Once the .getJSON request is finished, jQuery parses the JSON string that is returned from the file. When jQuery finds a property of the object that is a function, it executes it. Since your alert is a property of the object, it calls it.

This is a good illustration of why it is a bad idea to add methods to Object.prototype. Anything that tries to iterate through the properties of an object will also encounter the custom prototype properties.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.