覆盖功能(例如“警报”)并调用原始功能?

编程入门 行业动态 更新时间:2024-10-24 01:53:05
本文介绍了覆盖功能(例如“警报”)并调用原始功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想用一个调用原始版本的新版本覆盖Javascript内置函数(类似于在一个类上覆盖一个方法,其版本调用 super 在许多语言中)。我该怎么做?

I would like to override a Javascript built-in function with a new version that calls the original (similarly to overriding a method on a class with a version that calls super in many languages). How can I do this?

例如......

window.alert = function(str) { //do something additional if(console) console.log(str); //super.alert(str) // How do I do this bit? }

推荐答案

存储对原始文件的引用变量中的函数:

Store a reference to the original function in a variable:

(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) - 保留上下文并传递所有论点。通常,也应该返回原始方法的返回值。

The universal way is <original_func_reference>.apply(this, arguments) - To preserve context and pass all arguments. Usually, the return value of the original method should also be returned.

但是,已知 alert 是一个void函数,只接受一个参数,并且不使用这个对象。因此,在这种情况下, _alert(str)就足够了。

However, it's known that alert is a void function, takes only one argument, and does not use the this object. So, _alert(str) is sufficient in this case.

注意:IE< = 8会引发错误如果你试图覆盖 alert ,那么请确保你使用的是 window.alert = ... 而不是 alert = ... 。

Note: IE <= 8 throws an error if you try to overwrite alert, so make sure that you're using window.alert = ... instead of alert = ....

更多推荐

覆盖功能(例如“警报”)并调用原始功能?

本文发布于:2023-11-27 15:59:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1638657.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:功能   警报   原始

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!