3

I've built a GUI which passes in a long JS Object as settings for an animation plugin. One of the settings allows for the user to call a function once an animation is complete. Unfortunately, it has to be passed to the JS Object as a string.

... [ 'functioncall()' ] ......

Inside my animation callback, I'm retrieving this string and trying to run it as a function.

First attempt works perfectly, but uses eval...

eval( OS.path_jscall[index].path_jscall[0][i] )

I've setup a more preferred approach like so:

var HookFunction=new Function( OS.path_jscall[index].path_jscall[0][i] );
HookFunction();

Both examples call the functioncall() function perfectly. I'm not sure how to pass (this) to the functioncall() though...

functioncall(obj){ console.log(obj); };

Everything keeps referring to the window. Any ideas? Thanks!

Aaron
  • 2,482
  • 1
  • 26
  • 56

2 Answers2

3

Use .call when calling your function. .call assigns the first parameter to the this variable.

var myFunction = function(arg1, arg2) {
    alert(this);
}

myFunction.call(this, "arg1", "arg2");

Using your second example, you could do this:

HookFunction.call(this);
Kyle Trauberman
  • 25,414
  • 13
  • 85
  • 121
3

Assuming that HookFunction is the name, you can do either a call() or apply()

HookFunction.call(this,arg1,arg2,...,argN);

//or

HookFunction.apply(this,[arg1,arg2,...,argN]);

the basic difference of the 2 is that call() receives your "this" and an enumerated list of arguments after it, while apply() receives your "this" and an array of arguments

Joseph
  • 117,725
  • 30
  • 181
  • 234
  • Worked perfectly! Thank you so much, it needed an extra step of adding 'this' into the string call :) You're awesome! – Aaron Apr 25 '12 at 00:27