简体   繁体   中英

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'.

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
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');
});
var test;
(test = function( e ) { console.log('hello'+e); } )(); //helloundefined

test( ' world' ); //hello world

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM