Is it possible to add some code to existing javascript functions without modify original code? [duplicate]

我怕爱的太早我们不能终老 提交于 2019-12-06 08:52:59
Quentin

You can't modify functions, but you can wrap them and replace the function with the wrapper.

Such (see a live demo):

function logFactory(func, message) {
    return function () {
        console.log(message);
        return func.apply(this, arguments);
    }
}

hello = logFactory(hello, "Some log message");

This won't let you get any data while it is being manipulated by the function though or change what happens inside the function (although you can capture the arguments and modify them before passing them on, and you can capture the return value and modify it before returning it).

Ron van der Heijden

You could always use another function name and call the function you want to "extend"

function extendSomefunction(param) {
    somefunction(param);
    // additional things here
}

But another trick you can find here

Copied code:

var origParseFloat = parseFloat;
parseFloat = function(str) {
     alert("And I'm in your floats!");
     return origParseFloat(str);
}

The only other option you have, besides wrapping the functions inside new versions, is to modify the JavaScript files before they leave your server. Either manually, as a build step, or on the fly via an HttpHandler. This is the most robust solution since it also catches private functions and private references that are not exposed for you to wrap at runtime. However, it requires a lot of work, so if the simple function wrapping answer above is sufficient, I heartily recommend it!

You could wrap the function and replace it with the wrapper:

var originalHello;
originalHello = hello;

hello = function () {
    // log your stuff
    console.log('fired before original hello is triggered');

    // call original hello with the current scope & arguments
    originalHello.apply(this, arguments);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!