我可以命名一个 JavaScript 函数并立即执行它吗? [英] Can I name a JavaScript function and execute it immediately?

查看:32
本文介绍了我可以命名一个 JavaScript 函数并立即执行它吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多这样的:

function addEventsAndStuff() {
  // bla bla
}
addEventsAndStuff();

function sendStuffToServer() {
  // send stuff
  // get HTML in response
  // replace DOM
  // add events:
  addEventsAndStuff();
}

重新添加事件是必要的,因为 DOM 发生了变化,所以之前附加的事件都没有了.由于它们最初也必须附加(duh),因此它们具有很好的 DRY 功能.

Re-adding the events is necessary because the DOM has changed, so previously attached events are gone. Since they have to be attached initially as well (duh), they're in a nice function to be DRY.

这个设置没有问题(或者有没有问题?),但我可以稍微平滑一下吗?我想创建 addEventsAndStuff() 函数并立即调用它,所以它看起来不那么业余.

There's nothing wrong with this set up (or is there?), but can I smooth it a little bit? I'd like to create the addEventsAndStuff() function and immediately call it, so it doesn't look so amateuristic.

以下两个响应都出现语法错误:

Both following respond with a syntax error:

function addEventsAndStuff() {
  alert('oele');
}();

(function addEventsAndStuff() {
  alert('oele');
})();

有人接受吗?

推荐答案

您在问题中发布的示例没有任何问题.另一种做法可能看起来很奇怪,但是:

There's nothing wrong with the example you posted in your question.. The other way of doing it may look odd, but:

var addEventsAndStuff;
(addEventsAndStuff = function(){
    // add events, and ... stuff
})();

<小时>

在 JavaScript 中有两种定义函数的方法.一个函数声明:


There are two ways to define a function in JavaScript. A function declaration:

function foo(){ ... }

和函数表达式,这是定义上述函数以外的任何方法:

and a function expression, which is any way of defining a function other than the above:

var foo = function(){};
(function(){})();
var foo = {bar : function(){}};

...等

函数表达式可以命名,但它们的名称不会传播到包含范围.这意味着此代码有效:

function expressions can be named, but their name is not propagated to the containing scope. Meaning this code is valid:

(function foo(){
   foo(); // recursion for some reason
}());

但这不是:

(function foo(){
    ...
}());
foo(); // foo does not exist

因此,为了命名您的函数并立即调用它,您需要定义一个局部变量,将您的函数作为表达式分配给它,然后调用它.

So in order to name your function and immediately call it, you need to define a local variable, assign your function to it as an expression, then call it.

这篇关于我可以命名一个 JavaScript 函数并立即执行它吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆