最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Adding the same code to multiple functions - Stack Overflow

programmeradmin1浏览0评论

I am facing a situation where I need to add the same blocks of code to the start and the end of multiple functions in JavaScript. e.g.

function funcA () {
    // code block 1
    ...

    // code unique to funcA
    ...

    // code block 2
    ...
}

function funcB () {
    // code block 1
    ...

    // code unique to funcB
    ...

    // code block 2
    ...
}

function funcC () {
    // code block 1
    ...

    // code unique to funcC
    ...

    // code block 2
    ...
}

I wonder what is the right pattern to use here to minimize the duplications.

I am facing a situation where I need to add the same blocks of code to the start and the end of multiple functions in JavaScript. e.g.

function funcA () {
    // code block 1
    ...

    // code unique to funcA
    ...

    // code block 2
    ...
}

function funcB () {
    // code block 1
    ...

    // code unique to funcB
    ...

    // code block 2
    ...
}

function funcC () {
    // code block 1
    ...

    // code unique to funcC
    ...

    // code block 2
    ...
}

I wonder what is the right pattern to use here to minimize the duplications.

Share Improve this question asked Nov 15, 2012 at 18:18 MListerMLister 10.3k18 gold badges67 silver badges93 bronze badges 3
  • 1 Why not use functions for code block one and two? – adammenges Commented Nov 15, 2012 at 18:20
  • 1 @InBetween, i was hoping if there was a way similar to decorator in python... – MLister Commented Nov 15, 2012 at 18:45
  • I've provided a pattern below that solves this problem. It's like a diet-decorator. – elucid8 Commented Nov 15, 2012 at 19:57
Add a ment  | 

6 Answers 6

Reset to default 6

Its called the extract method refactoring.

function block1() 
{
  // code block 1
}

function block2() 
{
  // code block 2
}

function funcA () {
    block1();

    // code unique to funcA
    ....

    block2();
}
function funcB () {
    block1();

    //   code unique to funcB
    ....

    block2();
}
function funcC () {
    block1();

    //   code unique to funcC
    ....

    block2();
}

You could use another function to build your functions for you:

function makeFunc( specialProcessing ) {
  return function() {
    // block 1
    specialProcessing( x, y, z );
    // block 2
  };
}

var func1 = makeFunc( function( x, y, z ) {
  // stuff for func1
});

var func2 = makeFunc( function( x, y, z ) {
  // stuff for func2
});

If you have sizable chunks of code in these blocks that can be applied to each function universally, by simply changing the variables in use, then you should extract those blocks of codes to separate methods. This has the advantage of promoting code reuse, improving readability of your code, and making it much, much easier to test and debug, particularly if you're following test-driven development ideals or even just running your own functional testing. It is always a goal of good software engineering and design to create small methods that are useful in many places to reduce the work you have to do and decrease the number of bugs in your code.

Blocks can be extracted to functions and called using the apply method. This will keep context and forward any arguments passed to original function.

function funcA() {
    block1.apply(this, arguments);

    // specific code to funcA

    block2.apply(this, arguments);
}

arguments will contain any arguments passed to parent function

If you know it'll always be set up like that and you don't want to have the actual function calls inside of it, or maybe some will be in different orders I always like to set up a function to interwine the function calls for me.

jsFiddle DEMO

// Set up dynamically to handle calling any number of functions
// in whatever order they are specified in the parameters
// ie: setupFunctionOrder(func1, func2, func3, func4);

function setupFunctionOrder () {
    for (i = 0; i < arguments.length; i++) {
        arguments[i]();
    }
}

function block1 () { log('\nblock1 - running'); }
function block2 () { log('block2 - running'); }
function funcA () { log('funcA - running'); }

// ** Useage:
// now we make the actual call to set up the ORDER of calling -funcA-
setupFunctionOrder(block1, funcA, block2);

Just pass in the function you want to be unique. Like this:

function reusableFunc(fn) {
    //reused code block here
    fn();
    //reused code block here
}

var myResuableFunc1 = function (args) {
    reusableFunc(function () { 
        //do your business here.    
    });
};


var myResuableFunc2 = function (args) {
    reusableFunc(function () { 
        //do your business here.    
    });
};

//Or another way
function myResuableFunc3(args) {
    reusableFunc(function () { 
        //do your business here
    });
}

Then, you can create as many functions using the shared code as you want and, through the power of closures, pass these newly created functions around any way that you like.

发布评论

评论列表(0)

  1. 暂无评论