我想用一个新版本来调用原版JavaScript内置函数(类似于在许多语言中使用super
覆盖类中的方法)。我该如何做到这一点?
例如...
window.alert = function(str) {
//do something additional
if(console) console.log(str);
//super.alert(str) // How do I do this bit?
}
我想用一个新版本来调用原版JavaScript内置函数(类似于在许多语言中使用super
覆盖类中的方法)。我该如何做到这一点?
例如...
window.alert = function(str) {
//do something additional
if(console) console.log(str);
//super.alert(str) // How do I do this bit?
}
将原始函数的引用存储到变量中:
(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
};
})();
通用的方式是 <original_func_reference>.apply(this, arguments)
- 为了保留上下文并传递所有参数。通常应该返回原始方法的返回值。
但是,已知alert
是一个无返回值函数,仅接受一个参数,并且不使用this
对象。因此,在这种情况下,_alert(str)
足够了。
注意:如果尝试覆盖alert
,IE <= 8会抛出错误,因此请确保您使用window.alert = ...
而不是alert = ...
。
window.alert
,除了 IE <= 8。在 IE 9 之前,尝试覆盖 alert
会引发错误。 - Rob Wconfirm
,document
,... 如果你想拦截 window.alert
调用,你可以将代码包装在一个闭包中,在其中声明和定义一个自定义的 window
(或 alert
)变量。如果您的应用程序不依赖于隐式变量声明,则始终有效。 - Rob W没有"super"。无论如何,创建一个闭包来“保留”原始函数对象。
注意“自执行函数”,它返回一个新的函数对象(分配给window.alert
属性)。返回的新函数对象在变量original
周围创建了一个闭包,该闭包评估为传递给“自执行函数”的window.alert
的原始值。
window.alert = (function (original) {
return function (str) {
//do something additional
if(console) {
console.log(str)
}
original(str)
}
})(window.alert)
然而,我相信一些浏览器可能会阻止修改alert
和其他内置函数...
编程愉快。
我假设您的问题是如何覆盖内置函数并仍然能够调用它。首先作为免责声明,除非您有充分的理由,否则不应该覆盖内置函数,因为这将使调试/测试变得不可能。
以下是如何实现:
```window._alert = window.alert;
window.alert = function(str) {
if(console) console.log(str);
window._alert(str);
}
如何在Javascript中进行简单的经典继承:
SuperClass.call(this) // inherit from SuperClass (multiple inheritance yes)
this.myFunction = this.myFunction.override(
function(){
this.superFunction(); // call the overridden function
}
);
Function.prototype.override = function(func)
{
var superFunction = this;
return function()
{
this.superFunction = superFunction;
return func.apply(this,arguments);
};
};
可以使用多个参数。
尝试覆盖未定义或非函数时会失败。
使"superFunction"成为一个"保留"单词 :-)
window.alert = new Proxy(window.alert , {
apply: function(target,that,args){
console && console.log(args.join('\n'));
target.apply(that,args)
}})