window.alert = null;
alert('test'); // fail
delete window.alert; // true
alert('test'); // win
window
is an instance of DOMWindow
, and by setting something to window.alert
, the correct implementation is being "shadowed", i.e. when accessing alert
it is first looking for it on the window
object. Usually this is not found, and it then goes up the prototype chain to find the native implementation. However, when manually adding the alert
property to window
it finds it straight away and does not need to go up the prototype chain. Using delete window.alert
you can remove the window own property and again expose the prototype implementation of alert
. This may help explain:
window.hasOwnProperty('alert'); // false
window.alert = null;
window.hasOwnProperty('alert'); // true
delete window.alert;
window.hasOwnProperty('alert'); // false
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…