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 (_) { } } 
17
  • 6
    That shouldn't run the function. Can you show more context? Commented Oct 7, 2013 at 21:03
  • 1
    That does not run the function, sample: jsfiddle.net/PeAmw Commented Oct 7, 2013 at 21:04
  • 1
    Maybe you could cite your source, where did you see this? Commented Oct 7, 2013 at 21:05
  • 5
    @OBV: how about providing more code around and stopping wasting your and our time? Commented Oct 7, 2013 at 21:06
  • 1
    Are you sure there isn't a () at the end? That would explain it. Commented Oct 7, 2013 at 21:08

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

9 Comments

@mplungjan: I upvoted. Following that it is 1 of 7 (15%) I assume it was taxes.
@mplungjan - while a comment is always appreciated when there's a problem with an answer, whoever downvoted has no obligation to do so.
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
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.
I know it is not REQUIRED, just plain good manners! - I voted for the first couple of suggestions in your link
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.