Brandon Minton
Brandon Minton

Reputation: 1004

how can I call a JS self-executing function later if I want?

I am trying to write a function that executes immediately but can also be later like:

var test = function (e){ console.log('hello'+e); }();
$('#some_element').click(function(e){
    test(' world');
});

where in this case, the results I would want would be:

helloundefined
hello world

I am not grasping why calling test later returns 'test is not a function'.

Upvotes: 3

Views: 2380

Answers (4)

meouw
meouw

Reputation: 42140

var test;
(test = function( e ) { console.log('hello'+e); } )(); //helloundefined

test( ' world' ); //hello world

Upvotes: 3

icktoofay
icktoofay

Reputation: 129001

You define test like this:

var test = function (e){ console.log('hello'+e); }();

This creates a closure and then immediately calls it. Since there's no explicit return in the closure, it returns undefined. Now test contains undefined. Later, in the closure passed to click, it tries to call test. test is still undefined. You end up doing something like this:

undefined(' world');

You say you wanted it to output this:

helloundefined
hello world

In that case, you can do this:

var test = function test(e) { console.log('hello'+e); return test; }();

As a side effect, it also makes test chainable, so you could do this:

test(" world")(" stack overflow")(" internet");

And the result (excluding the first helloundefined) would be:

hello world
hello stack overflow
hello internet

Upvotes: 6

JW.
JW.

Reputation: 51648

You're assigning the return value of the function to test, not the function itself. I don't think you can use the self-executing shortcut if you also want to assign it to a variable. You'll need to do:

var test = function (e){ console.log('hello'+e); };
test();
$('#some_element').click(function(e){
    test(' world');
});

Upvotes: 1

Jon
Jon

Reputation: 437386

var test = function (e){ console.log('hello'+e); }();

Those parens at the end mean that test is the result of evaluating a function call (in other words the return value of the function), not the function itself.

Try this:

var testFunc = function (e){ console.log('hello'+e); };
testFunc();
$('#some_element').click(function(e){
    testFunc(' world');
});

Upvotes: 4

Related Questions