javascript中的init函数及其工作原理 [英] Init function in javascript and how it works

查看:162
本文介绍了javascript中的init函数及其工作原理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常看到以下代码:

(function () {
  // init part
})();

但我永远无法理解它是如何运作的。我发现最后一个括号特别令人困惑。
有人可以解释它在执行上下文(EC)和变量对象(VO)方面是如何工作的吗?

but I never could get my head around how it works. I find the last brackets especially confusing. Could someone explain how it works in terms of Execution Contexts (EC) and Variable Objects (VO)?

推荐答案

该模式将创建一个新的执行上下文(EC),其中任何本地变量对象(VO)将存在,并且当EC退出时同样会死亡。这一生命中唯一的例外是VO,它成为关闭的一部分。

That pattern will create a new execution context (EC) in which any local variable objects (VO's) will live, and will likewise die when the EC exits. The only exception to this lifetime is for VO's which become part of a closure.

请注意,JavaScript没有神奇的初始化功能。您可以将此模式与此类型相关联,因为大多数任何自尊的JS库(jQuery,YUI等)都会执行此操作,以便它们不会污染全局NS,而不是他们需要的。

Please note that JavaScript has no magic "init" function. You might associate this pattern with such since most any self-respecting JS library (jQuery, YUI, etc.) will do this so that they don't pollute the global NS more than they need to.

示范:

var x = 1; // global VO
(function(){        
    var x = 2; // local VO
})();
x == 1; // global VO, unchanged by the local VO

第二组括号(实际上是那些)称为parens或一组括号,只是调用它前面的函数表达式(由前面的括号组定义)。

The 2nd set of "brackets" (those are actually called parens, or a set of parentheses), are simply to invoke the function expression directly preceding it (as defined by the prior set of parenthesis).

这篇关于javascript中的init函数及其工作原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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