有人有在JavaScript中重写alert()函数的经验吗?

哪些浏览器支持这个功能? 哪些浏览器版本支持此功能? 重写函数的危险是什么?


当前回答

超铃报警功能无危险。每个浏览器都支持它。

例如:

// function over riding. Redirecting to Console with Firebug installed.
function alert(message) { 
    console.info(message);
} 

alert('This is an override.');

其他回答

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.

尽管大多数浏览器支持重写它,但要小心使用它所做的事情。

由于默认的警告框阻塞了执行线程,一些依赖此行为的库可能不再工作(充其量)。

您应该做一个好公民,避免接触本机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实现都支持重写。

危险很简单,如果您重写了诸如alert()这样的常见函数,就会把其他团队成员逼疯。

所以除非你重写函数作为调试或修改现有代码的工具,否则我认为没有任何理由这样做。只需要创建一个新函数。

我重写alert()函数的经验是,我们曾经使用它来“破解”JavaScript库的试用版,该库在每次提醒时都显示“请注册!”的提示屏幕。

我们刚刚定义了自己的alert()函数,瞧。

这只是为了测试,我们后来买了完整版,所以这里没有什么不道德的事情;-)

正如在许多其他答案中所述,您可以使用

window.alert = null

or

window.alert = function(){}

然而,这并不一定会覆盖Window构造函数原型上的函数(注意大写的W),所以黑客仍然可以输入:

Window.prototype.alert.apply(window, ["You were hacked!"]);

因此,你还需要重写该函数:

Window.prototype.alert = null

or

Window.prototype.alert = function(){}