繁体   English   中英

我可以使用与现有名称相同的名称创建自己的函数来自定义吗?

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

我有一些console.log命令通过我的网站传播。

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

最后,我仍然需要从这个函数调用真正的console.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);
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM