如果我想,如何稍后调用JS自执行函数?

Bra*_*ton 3 javascript jquery

我正在尝试编写一个立即执行的函数,但也可以在以后执行:

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

在这种情况下,我想要的结果是:

helloundefined
hello world

我没有理解为什么调用测试后来返回'测试不是一个函数'.

ick*_*fay 6

你这样定义test:

var test = function (e){ console.log('hello'+e); }();
Run Code Online (Sandbox Code Playgroud)

这会创建一个闭包,然后立即调用它.由于return闭包中没有显式,因此返回undefined.现在test包含undefined.后来,在关闭传递给click它时,它试图调用test.test还在undefined.你最终会做这样的事情:

undefined(' world');
Run Code Online (Sandbox Code Playgroud)

你说你希望它输出这个:

helloundefined
hello world
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您可以这样做:

var test = function test(e) { console.log('hello'+e); return test; }();
Run Code Online (Sandbox Code Playgroud)

作为副作用,它也可以制作test链式,所以你可以这样做:

test(" world")(" stack overflow")(" internet");
Run Code Online (Sandbox Code Playgroud)

结果(不包括第一个helloundefined)将是:

hello world
hello stack overflow
hello internet
Run Code Online (Sandbox Code Playgroud)