我想用一个调用原始版本的新版本覆盖一个Javascript内置函数(类似于用一个调用super多种语言版本的类重写一个方法).我怎样才能做到这一点?
例如...
window.alert = function(str) {
//do something additional
if(console) console.log(str);
//super.alert(str) // How do I do this bit?
}
Run Code Online (Sandbox Code Playgroud)
Rob*_*b W 46
在变量中存储对原始函数的引用:
(function() {
var _alert = window.alert; // <-- Reference
window.alert = function(str) {
// do something additional
if(console) console.log(str);
//return _alert.apply(this, arguments); // <-- The universal method
_alert(str); // Suits for this case
};
})();
Run Code Online (Sandbox Code Playgroud)
通用方法是<original_func_reference>.apply(this, arguments)- 保留上下文并传递所有参数.通常,还应返回原始方法的返回值.
但是,已知它alert是一个void函数,只接受一个参数,并且不使用该this对象.所以,_alert(str)在这种情况下就足够了.
注意:如果您尝试覆盖alert,IE <= 8会引发错误,因此请确保使用window.alert = ...而不是alert = ....
小智 21
没有"超级".无论如何,创建一个闭包以"保持"原始函数对象.
请注意"自调用函数",它返回一个新的函数对象(分配给该window.alert属性).返回的新函数对象周围产生一个闭合变量 original,其计算结果为原始值的window.alert,在"自主调用功能"获得通过.
window.alert = (function (original) {
return function (str) {
//do something additional
if(console) {
console.log(str)
}
original(str)
}
})(window.alert)
Run Code Online (Sandbox Code Playgroud)
但是,我相信一些浏览器可能会阻止alert和其他内置版本被修改...
快乐的编码.
我假设您的问题是如何覆盖内置并仍然可以调用它.首先作为免责声明,你绝不应该覆盖内置的ins,除非你有充分的理由这样做,因为它将无法进行调试/测试.
这是你怎么做的:
window._alert = window.alert;
window.alert = function(str) {
if(console) console.log(str);
window._alert(str);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28492 次 |
| 最近记录: |