当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 一道js代码填空题的解 window.alert = function(){};____;alert(1);

一道js代码填空题的解 window.alert = function(){};____;alert(1);

2017年12月21日  | 移动技术网IT编程  | 我要评论
[javascript]  

window.alert = function(){}; //覆盖了alert方法   

//这里写些代码将alert还原   

alert(1); //这里要求还能弹出alert对话框  

 

window.alert = function(){}; //覆盖了alert方法

//这里写些代码将alert还原

alert(1); //这里要求还能弹出alert对话框

记录这个话题是因为微博上有人讨论到了,我直接写答案了。

 

 

 

 

方法1,直接删除 alert。

 

 

[javascript] 

window.alert = function(){};  

delete alert;  

alert(1);  

 

window.alert = function(){};

delete alert;

alert(1);这个代码是最简单、效果最好的,推荐。

 

 

 

 

方法2,从原型链上找回原本的alert方法。

 

alert是window的方法,因此找到window.constructor.prototype.alert,再调用call或者apply即可。

 

 

[javascript] 

window.alert = function(){};  

window.alert = function(s){window.constructor.prototype.alert.call(window,s);};  

alert(1);  

 

window.alert = function(){};

window.alert = function(s){window.constructor.prototype.alert.call(window,s);};

alert(1);重新定义了一个函数再去覆盖,后面的alert是这个函数而不是真正原本的alert. 

 

window.constructor是兼容性比较好的,如果使用Window对象则IE不支持。

 

 

 

 

 

方法3,iframe法。

 

新建一个空白iframe,这个iframe里的DOM就是干净的了,将这个iframe里的alert引用出来,也能让警告对话框弹出。

 

我只能说,想出这个方法的人真是不懂JS。

 

 

 

 

 

代码写的多写的复杂,并不代表水平高。

 

真正的代码高手,总是把代码写的更少、更简单。

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网