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

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

问题描述

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

函数sendStuffToServer(){
//发送东西
//获取HTML中的响应
//替换DOM
//添加事件:
addEventsAndStuff();

$ / code>

重新添加事件是必要的,因为DOM已经改变,事件消失了。由于它们最初也需要附加(duh),所以它们处于干燥状态。



此设置没有任何问题(或者是否存在?),但我可以平滑一点吗?我想创建 addEventsAndStuff 函数并立即调用它,所以它看起来不像是一个非常有趣的。



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

pre $ function $ addEventsAndStuff
}();

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

任何购买者?

解决方案

您在问题中发布的示例没有任何问题。执行此操作的另一种方式可能看起来很奇怪,但是:

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






在JavaScript中定义函数有两种方法。函数声明:

  function foo(){...} 

和一个函数表达式,它是 任何 定义除上述函数之外的函数的方式: p>

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

... etc

函数表达式可以被命名,但他们的名字不会传播到包含范围。这个代码的含义是有效的:

 (function foo(){
foo(); //由于某种原因递归
}());

但这不是:

 (function foo(){
...
}());
foo(); // foo不存在

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


I have quite a few of these:

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

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

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.

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

Any takers?

解决方案

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


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(){}};

...etc

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

but this isn't:

(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天全站免登陆