window.alert无法删除

window.alert cannot be deleted

本文关键字:删除 alert window      更新时间:2023-09-26

我读到了关于JavaScript删除运算符的文章,并对其进行了实验。在我尝试从窗口对象中删除一个方法之前,一切似乎都很好。代码看起来像

var log = function(str){
  if(str !== undefined)
  {
    document.write(str);
  }
   document.write("</br>");
};

window.myVar = function(){
  // do something
};
// this deletes custom method 
log(delete  window.myVar);  // true (expected)
log(typeof window.myVar);  // undefined (expected)
log(delete window.alert);  // true (OK)
log(typeof window.alert); // function (Unexpected)
window.alert = 10;
log(typeof window.alert);   // number (Successfully overwritten)
log(delete window.alert);  // true
log(typeof window.alert); // function (Returns back to original object)

它似乎可以让我删除我创建的对象,但不能删除已经定义的对象,而是让我覆盖它。有人能解释一下背后的原因吗?此外,如果delete未能删除此处也未发生的对象,则应返回"false"。

[更新]我正在使用FF 19并在http://jsbin.com

[Update]请注意,我了解如何覆盖window.alert并运行我的自定义代码。我的问题是window.alert有什么特别之处,以至于它无法删除,但删除返回true?我知道这是一个原生对象,但这并不能解释为什么这是不可能的。是浏览器JavaScript引擎在我的代码删除警报方法后重新添加的吗?。另外,我是否可以编写类似的函数,而使用我的库的另一个用户无法删除,只能覆盖它?怎样

简单地说,我们可以覆盖现有的函数,但不能擦除它们。当在现有/标准函数上调用delete时,它会重置为标准原型。但如果你确实想中和函数,比如windows.alert,那么就分配一个空白函数,如下所示:

window.alert = function(){}; //blank function makes window.alert now useless 

尝试基于控制台(浏览器)的脚本:

window.alert = function(data){
    console.log('alerting:'+data)
}; 
window.alert('hi'); // this will print "alerting:hi" in console
delete window.alert
window.alert('hi'); // now this will show regular alert message box with "hi" in it

我希望这能解释它。

更新:

假设你想覆盖一个标准功能"警报",然后:

//this function will append the data recieved to a HTML element with 
// ID message-div instead of showing browser alert popup
window.alert = function(data){
    document.getElementById('message-div').innerHTML = data;
}
alert('Saved Successfully'); //usage as usual
...
//when you no longer need custom alert then you revert to standard with statement below
delete window.alert;