Aaron
Aaron

Reputation: 2500

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!

Upvotes: 3

Views: 352

Answers (2)

Kyle Trauberman
Kyle Trauberman

Reputation: 25684

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);

Upvotes: 3

Joseph
Joseph

Reputation: 119837

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

Upvotes: 3

Related Questions