有人有在JavaScript中重写alert()函数的经验吗?
哪些浏览器支持这个功能? 哪些浏览器版本支持此功能? 重写函数的危险是什么?
有人有在JavaScript中重写alert()函数的经验吗?
哪些浏览器支持这个功能? 哪些浏览器版本支持此功能? 重写函数的危险是什么?
当前回答
Ladislav。 对于IE8,你可以像这样重新定义alert()
/**
* Definition of global attached to window properties <br/>
*/
(function() {
nalert = window.alert;
Type = {
native: 'native',
custom: 'custom'
};
})();
/**
* Factory method for calling alert().
* It will be call a native alert() or a custom redefined alert() by a Type param.
* This defeinition need for IE
*/
(function(proxy) {
proxy.alert = function () {
var message = (!arguments[0]) ? 'null': arguments[0];
var type = (!arguments[1]) ? '': arguments[1];
if(type && type == 'native') {
nalert(message);
}
else {
document.write('<h1>I am redefiend alert()<br/>Alert say: '+message+'</h1>');
}
};
})(this);
并调用as
alert('Hello, hacker!');
nalert('I am native alert');
alert('Hello, user!', Type.custom);
其他回答
超铃报警功能无危险。每个浏览器都支持它。
例如:
// function over riding. Redirecting to Console with Firebug installed.
function alert(message) {
console.info(message);
}
alert('This is an override.');
它绝对是“支持的”。这是你的网页,你想做什么就做什么。
我已经这样做了,在不修改库的情况下跟踪分析事件,但通过潜入事件。
使用代理模式:
(function(proxied) {
window.alert = function() {
// do something here
return proxied.apply(this, arguments);
};
})(window.alert);
如果需要,还可以绕过对原始函数的调用(代理)
更多信息:JQuery类型#代理模式
尽管大多数浏览器支持重写它,但要小心使用它所做的事情。
由于默认的警告框阻塞了执行线程,一些依赖此行为的库可能不再工作(充其量)。
您应该做一个好公民,避免接触本机API。如果你这样做了,当你使用第三方代码时,你可以把事情分开。
然而,如果你想在特定的上下文中重新定义警报行为,你可以用一个匿名函数来包围它,就像这样:
/* new funky alert */
function myFunkyAlert(msg) {
/* here goes your funky alert implementation */
alert("Look ma!\n" + msg);
}
(function(alert) { // anonymous function redefining the "alert"
/* sample code */
alert("Hello World!");
})(myFunkyAlert);
我认为每个Javascript实现都将支持这一点,并且这样做不会有任何危险。通常用HTML/CSS代替简单的os风格的警告框。这样做意味着您不必更改现有的代码!这一事实使得Javascript非常棒。
When it comes to js browser functions window.alert is pre-eminent and most well known, people who don't know js know alert() -- rest assured it is supported in all browsers in use today and your code snippet is as well. However, I wouldn't override (well this is more like refactoring rather than override in the OOP sense) alert() for a particular use case as yours because when you actually need to use alert() with no template, and you probably will, then you'll need another non-alert function to do so.