admin管理员组

文章数量:1279011

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

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

Share Improve this question asked Apr 24, 2011 at 23:45 Brandon MintonBrandon Minton 1,0044 gold badges15 silver badges26 bronze badges 2
  • 1 if you define "test" within the body of another function it is possible that the variable "test" goes out of scope. – Jaime Garcia Commented Apr 24, 2011 at 23:47
  • 1 you are storing the return value of the function into test. – ySgPjx Commented Apr 24, 2011 at 23:47
Add a ment  | 

4 Answers 4

Reset to default 6

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

本文标签: javascripthow can I call a JS selfexecuting function later if I wantStack Overflow