我试图编写一个可以立即执行的函数,但稍后也可以像这样:

var test = function(e){console.log('hello'+ e); }();
$('#some_element')。click(function(e){
测试('世界');
});

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

你好未定义
你好,世界

我不明白为什么稍后调用test会返回“test is a not function”。

最佳答案

您可以这样定义test:

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

这将创建一个闭包,然后立即调用它。由于闭包中没有显式的return,因此它返回undefined。现在test包含undefined。稍后,在传递给click的闭包中,它尝试调用testtest仍然是undefined。您最终会执行以下操作:
undefined(' world');

您说您想要它输出此:
helloundefined
hello world

在这种情况下,您可以执行以下操作:
var test = function test(e) { console.log('hello'+e); return test; }();

副作用是,它也使test可链接,因此您可以执行以下操作:
test(" world")(" stack overflow")(" internet");

结果(不包括第一个helloundefined)将是:
hello world
hello stack overflow
hello internet

10-05 20:37
查看更多