我可以创建自己的函数与现有函数同名以自定义它吗?

Can I create my own function with the same name as an existing to customize it?

本文关键字:函数 自定义 自己的 创建 我可以      更新时间:2023-09-26

我有一些控制台.log命令在我的网站上传播。

是否可以使用我自己的函数覆盖控制台.log? 我想自定义函数,以便它仅在特定变量设置为 true 时记录。

最后,我仍然需要从这个函数调用真正的控制台.log。

谢谢凯文

只需创建一个闭包,并将原始console.log函数存储在局部变量中。
然后覆盖console.log,并在执行检查后调用原始函数:

(function(){
    var original = console.log;
    console.log = function(){
        if ( log ) { // <-- some condition
            original.apply(this, arguments);
        }
    };
})();

这是小提琴:http://jsfiddle.net/J46w8/

首先保存旧console.log()

var reallog = console.log;
console.log = function(s) {
    if(s == "a") {
        reallog("a");
    }
}
console.log("b");
console.constructor.prototype.log = function(msg) {
    alert(msg);
};