0

I'm trying to insert some content in a defined function, something like this:

var f = function(){
   alert("Hello");
};

var e = function(){
   alert('Hey');
};
    f = f + e;
f();

the output will be: "Hello", and then another alert with "Hey".

Is it possible to do something like this? Please help.

4 Answers 4

1

Only thing I could imagine (but the question is whether it makes much sense) is something like this:

function combine() {
    var func = arguments;
    return function() {
        for(var i = 0; i < func.length; i++) {
            if(typeof func[i] == 'function') {
                func[i]();
            }
        }
    }
}

and then:

f = combine(f,e);
f();

DEMO

But this is just executing the functions one after another, you don't have access to variables declared in other functions, and return values are lost.

Sign up to request clarification or add additional context in comments.

Comments

1

You can pass one function into another as an argument, which can call its function parameter.

Example: http://jsfiddle.net/ybNu9/

var f = function( fn ){
   alert("Hello");
   fn();
};

var e = function(){
   alert('Hey');
};

f( e );

Of course, this requires the anticipation of such a parameter in the f function.

2 Comments

You could do it the other way around, have e call f, and avoid previous knowledge in f.
@Juan - Very true, though e would need previous knowledge of f. It would be helpful to know more about OP's actual situation.
0

no, it is against any "normal" programming convention. Writing a=f+e would concatenate their return values, that is all you could do to at least simulate behaviour you want. Writing f=f+e is illegal.

Comments

0

You can't "insert" code into a function, I suppose the closest you can do is re-define the original function, for example:

var old_f = f;
f = function() { old_f(); alert('Hey'); };

Though...I can't think of a generic good reason to do this (there's a better solution in most cases), can you not run an additional function, or call both? for example:

function newFunc() { f(); e(); }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.