[英]window.alert cannot be deleted
我正在阅读有关JavaScript删除运算符的文章,并对其进行了试验。 一切似乎都很好,直到我尝试从window对象中删除一个方法。 代码如下
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未能删除此处未发生的对象,则delete也应返回“ false”。
[更新]我正在使用FF 19并在http://jsbin.com中运行它
[更新]请注意,我了解如何覆盖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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.