有人有在JavaScript中重写alert()函数的经验吗?
哪些浏览器支持这个功能? 哪些浏览器版本支持此功能? 重写函数的危险是什么?
有人有在JavaScript中重写alert()函数的经验吗?
哪些浏览器支持这个功能? 哪些浏览器版本支持此功能? 重写函数的危险是什么?
当前回答
我重写alert()函数的经验是,我们曾经使用它来“破解”JavaScript库的试用版,该库在每次提醒时都显示“请注册!”的提示屏幕。
我们刚刚定义了自己的alert()函数,瞧。
这只是为了测试,我们后来买了完整版,所以这里没有什么不道德的事情;-)
其他回答
它在firefox和ie8中确实有效。我看不出有什么浏览器是它不能运行的。这是javascript工作的基本原理,尽管人们不经常看到它与原生函数一起使用=)
我重写alert()函数的经验是,我们曾经使用它来“破解”JavaScript库的试用版,该库在每次提醒时都显示“请注册!”的提示屏幕。
我们刚刚定义了自己的alert()函数,瞧。
这只是为了测试,我们后来买了完整版,所以这里没有什么不道德的事情;-)
超铃报警功能无危险。每个浏览器都支持它。
例如:
// function over riding. Redirecting to Console with Firebug installed.
function alert(message) {
console.info(message);
}
alert('This is an override.');
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);
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.