Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
677 views
in Technique[技术] by (71.8m points)

merge - Adding code to a javascript function programmatically

I'm attempting to customize an existing JS library without modifying the original JS code. This code loads in a few external JS files which I do have access to, and what I'd like to do is change one of the functions contained in the original file without copying and pasting the whole thing into the second JS file.
So for example, the off limits JS might have a function like this:

var someFunction = function(){
    alert("done");
}

I'd like to be able to somehow append or prepend some JS code into that function. The reason is primarily that in the original untouchable JS the function is pretty enormous and if that JS ever gets updated, the function I overwrite it with will be out of date.

I'm not entirely sure this is possible, but I figured I'd check.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If someFunction is globally available, then you can cache the function, create your own, and have yours call it.

So if this is the original...

someFunction = function() {
    alert("done");
}

You'd do this...

someFunction = (function() {
    var cached_function = someFunction;

    return function() {
        // your code

        var result = cached_function.apply(this, arguments); // use .apply() to call it

        // more of your code

        return result;
    };
})();

Here's the fiddle


Notice that I use .apply to call the cached function. This lets me retain the expected value of this, and pass whatever arguments were passed in as individual arguments irrespective of how many there were.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...