The delete operator removes a property from an object. If I set a property on window, I can delete it:
window.myProp = 10;
delete window.myProp;
As the article I so often refer others to when it comes to the behaviour of the delete operator states, this is because property assignment does not set the DontDelete attribute (as opposed to variable declaration, which does).
That article also states the following (emphasis added):
Note that it is during property creation that attributes are
determined (i.e. none are set). Later assignments don’t modify
attributes of existing property. It’s important to understand this
distinction.
Bearing that in mind, why can I override an existing property of window, alert, and then delete it to return to the original value? Am I missing something obvious? I rarely use the delete operator so that may well be the case.
For example:
window.alert = function() {};
alert("Hi!"); //Nothing happens
delete window.alert;
alert("Hello?"); //Alerts 'Hello?'
Here’s a fiddle to demonstrate that (only tested in Chome, pretty sure IE will not behave this way but don’t have access to anything but Chrome right now).
In Chrome, the
window.alertfunction is part of the prototype of theDOMWindowclass, it’s not a property ofwindowitself.Hence when you overwrite
window.alertyou’re adding a new property towindow, but the version in the prototype continues to exist, but is hidden.When you
delete window.alertthe function in the prototype is re-exposed.Here’s some console output showing that the function is in the prototype:
Firefox behaves similarly, albeit with different class names.