最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

What are self-calling functions in JavaScript? - Stack Overflow

programmeradmin2浏览0评论

From what I have heard, the following is a "self-calling function":

func(){}();

How is it different from the following?

func(){} func();

From what I have heard, the following is a "self-calling function":

func(){}();

How is it different from the following?

func(){} func();
Share Improve this question edited Sep 22, 2011 at 17:52 Tomasz Nurkiewicz 341k71 gold badges712 silver badges679 bronze badges asked Sep 22, 2011 at 13:13 wOlVeRiNewOlVeRiNe 5751 gold badge5 silver badges21 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 12

I assume you meant what is the difference between (I):

function(){}();

and (II):

function func(){};
func();

or even (III):

var func = function(){};
func();

All three behave the same in regard to the results, however they have different naming and scoping consequences:

  • I: this will not make the function available under any name, it is run once and forgotten. You can not reference it in the future

  • II: func function is created and available in the whole enclosing function, even before it is defined (hoisting)

  • III: func variable is defined pointing to a function. It won't be accessible before being defined.

Note that in II and III the function is referencable via func name and can be called again multiple times. This is not possible with self-calling function in I.

发布评论

评论列表(0)

  1. 暂无评论