0

See the below javascript. When functions are arrangment this way, how is it that they are able to run without being called specifically. What I mean is that the function below runs without being called and I don't understand how.

(j, function() {
alert(1);
})

it is eval'd like this:

eval(s)(j, function() { catch (_) { } } 
mplungjan
  • 169,008
  • 28
  • 173
  • 236
OBV
  • 1,169
  • 1
  • 12
  • 25

1 Answers1

11

It looks like those are the arguments to a function call, ie

foo(j, function() {
   alert(1);
})

That will pass the current value of j as the first argument, and the function listed there as the second argument.

That said, in order for that function—the one that alerts 1—to be called, foo would have to manually call it. Something along the lines of

function foo(j, f){
    f();
}

EDIT

So, per your question edit, it looks like what's above is more of less correct, except instead of referencing the function directly, you're fetching it from an eval statement.

Something like this:

function foo(j, f){
     f();
}
var s = "foo";
var j = 0;
eval(s)(j, function() {
    alert(1);
})

Here's a working FIDDLE

Adam Rackis
  • 82,527
  • 56
  • 270
  • 393
  • 6
    @mplungjan: I upvoted. Following that it is 1 of 7 (15%) I assume it was taxes. – zerkms Oct 07 '13 at 21:08
  • @mplungjan - while a comment is always appreciated when there's a problem with an answer, whoever downvoted has no obligation to do so. – Adam Rackis Oct 07 '13 at 21:08
  • Yes they do. Unless there is a comment already that the downvoter can agree with, it is friggin mandatory to leave a message or stop using SO – mplungjan Oct 07 '13 at 21:09
  • 2
    I didn't vote on this, but the downvoter might have considered this a guess. There's a chance it's a function call, but if there's missing code it could also be an IIFE. – bfavaretto Oct 07 '13 at 21:09
  • @AdamRackis I also upvoted, but you should mention that `foo` has to call the second parameter. Just passing it doesn't run it, of course. – ComFreek Oct 07 '13 at 21:10
  • @ComFreek: "has to call the second parameter" --- it's a second level guess :-) – zerkms Oct 07 '13 at 21:11
  • @zerkms Waiting for more taxes to come :) You're in my profile, now. I hope you don't mind :D – ComFreek Oct 07 '13 at 21:14
  • @mplungjan Commenting while downvoting is not required at all, the see discussion at http://meta.stackexchange.com/questions/135/encouraging-people-to-explain-downvotes – bfavaretto Oct 07 '13 at 21:17
  • 1
    I know it is not REQUIRED, just plain good manners! - I voted for the first couple of suggestions in your link – mplungjan Oct 07 '13 at 21:18