woojoo666
woojoo666

Reputation: 7921

Javascript closure: dynamically-defined functions, call method from current scope

Is it possible to have a static function that calls a dynamically defined function? I need this because I can't change the static function, and all I know is that it calls the dynamic function. For example:

function staticFunc() {
  dynamicFunc();
}

function test() {
  function dynamicFunc() {console.log('yay');}
  staticFunc();
};

test();

but it gives me the error dynamicFunc is not defined.

I know that if I hardcode staticFunc in test(), it works. I also noticed that I only get the error when I call staticFunc, not when I define it (even though dynamicFunc is not defined yet), which makes it seem like staticFunc is running inside test()'s scope, but evidently not.

Any way to do this? The only way I can think of is to make a global function funcPtr that gets assigned to my dynamic function.

Upvotes: 0

Views: 130

Answers (2)

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28558

Closure is you can use variable of parent level scope in child level scope. Here in your case it is reverse you have initialize a function in a child level scope and try to invoke it in parent scope which is not correct.

You may pass current function as parameter and invoke it:

Here is Demo

function staticFunc(dynamicFunc) {
  dynamicFunc();
}

function test() {
  var dynamicFunc = function() {console.log('yay');}
  staticFunc(dynamicFunc);
};

test();

Upvotes: 2

DontVoteMeDown
DontVoteMeDown

Reputation: 21465

Try this:

var dynamicFunc = null;
function test() {
    dynamicFunc = function () {console.log('yay');}
    staticFunc();
};

Considering that you can't change anything on your static function, the solution changes the declaration of dynamicFunc to a var that contains a function.

This can throw an exception if the static function tries to call dynamicFunc when its null. But you can declare as this:

var dynamicFunc = function() {};

Fiddle.

Upvotes: 1

Related Questions