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

会有一股神秘感。 提交于 2019-12-10 11:33:32

问题


There is some javascript code, e.g.

function hello() {
}
function world() {
}

I want to add some logging code to them, but I don't want to modify the code. I hope I can write some code in another file, and it will modify the functions at runtime. It is possible to do this?


Update

Thanks for the two answers, but I have to make this question clearer.

The hello and world functions are just some samples, actually there are hundreds of functions in the file, it's implement to redefine them manually.

I'm looking for a way to do this automatically (similar to AspectJ in java).


回答1:


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).




回答2:


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);
}



回答3:


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!




回答4:


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);
}


来源:https://stackoverflow.com/questions/15251030/is-it-possible-to-add-some-code-to-existing-javascript-functions-without-modify

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!