Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid EVAL and pass THIS to function?

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!

like image 218
Aaron Avatar asked Sep 02 '26 16:09

Aaron


2 Answers

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

like image 94
Joseph Avatar answered Sep 04 '26 05:09

Joseph


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);
like image 36
Kyle Trauberman Avatar answered Sep 04 '26 05:09

Kyle Trauberman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!