在引用原始函数时覆盖JavaScript函数 [英] Overriding a JavaScript function while referencing the original

查看:137
本文介绍了在引用原始函数时覆盖JavaScript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数, a(),我要覆盖它,但也有原始 a()根据上下文按顺序执行。例如,有时当我生成一个页面时,我想要覆盖如下:

I have a function, a(), that I want to override, but also have the original a() be performed in an order depending on the context. For example, sometimes when I'm generating a page I'll want to override like this:

function a() {
    new_code();
    original_a();
}

有时候会这样:

function a() {
    original_a();
    other_new_code();
}

如何获得 original_a()来自覆盖 a()?它甚至可能吗?

How do I get that original_a() from within the over-riding a()? Is it even possible?

请不要以这种方式建议替代方案,我知道很多。我是专门问这个问题的。

Please don't suggest alternatives to over-riding in this way, I know of many. I'm asking about this way specifically.

推荐答案

你可以这样做:

var a = (function() {
    var original_a = a;

    if (condition) {
        return function() {
            new_code();
            original_a();
        }
    } else {
        return function() {
            original_a();
            other_new_code();
        }
    }
})();

在匿名函数中声明 original_a 保留它从混乱的全局命名空间,但它在内部函数中可用。

Declaring original_a inside an anonymous function keeps it from cluttering the global namespace, but it's available in the inner functions.

与评论中提到的Nerdmaster一样,请务必包含()最后。你想调用外部函数并将结果(两个内部函数之一)存储在 a 中,而不是将外部函数本身存储在 a

Like Nerdmaster mentioned in the comments, be sure to include the () at the end. You want to call the outer function and store the result (one of the two inner functions) in a, not store the outer function itself in a.

这篇关于在引用原始函数时覆盖JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆