JavaScript设计模式需要帮助:模块扩展松散 [英] JavaScript Design Patterns Help Needed: Loose Augmentation of Modules

查看:121
本文介绍了JavaScript设计模式需要帮助:模块扩展松散的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了清楚起见,编辑 - @ Qantas94Heavy - 我明白是什么说或应该做的,我不明白是为什么&更重要的是,它如何工作:

Edit for clarity - @Qantas94Heavy - I understand what it is "saying" or supposed to do, what I don't understand is why & more importantly how it works:

我正在阅读JS模块模式的高级教程,并给出了这个例子:

I was reading an advanced tutorial on the JS Module Pattern, and it gave this example:

var MODULE = (function (my) {
// add capabilities...

return my;
}(MODULE || {}));

是我最后一个声明(和我需要你的帮助)的事情是: p>

The thing that is bugging me (and I need your help with) is the last statement:

(MODULE || {}));

我无法理解背后的语法规则,使之成为可能。在搜索关键字JavaScript模块语法和模块模式短手之后,我发现我还不太了解这个基础。

i'm having trouble understanding the syntax rules behind this that make it possible. After doing some searching for keywords, "JavaScript Module Syntax", and "Module Pattern Short Hand" I found that I'm still not quite understanding the foundation behind this.

有人请您解释或指出我正确的方向,以征服这个/获得更深入的了解吗?

Would someone please explain or point me in the right direction for grokking this/gaining a deeper understanding?

真诚的,
gggi

Sincerely, gggi

推荐答案

(function(){

})();

是一个自我调用的匿名函数。在你的情况下,它处理我的对象参数:它做一些我的,然后返回。

is a self-invoking anonymous function. In your case, it handles the "my" object parameter: it does something to "my" and then returns it back.

在你的情况下,函数接收的my参数是(MODULE || {})。

In your case the "my" parameter the function receives is "(MODULE || {})".

&&和||运营商称为短路运营商。 ||将返回,如果MODULE对象存在,则MODULE对象,否则将创建一个空对象,以在函数内部使用。该函数将对该对象执行任何操作,这将成为返回的MODULE对象。

The && and || operators are called short-circuit operators. || will return, if "MODULE" object exists, the "MODULE" object, otherwise, an empty object will be created to be used inside the function. The function will do whatever it does to that object, which will became the returned "MODULE" object.

它通过创建一个闭包来工作:只要MODULE存在(它是不是垃圾收集),所以自动调用匿名函数以及在分配时的状态。这使得添加的任何功能都将持续存在。

It works by creating a closure: as long as MODULE exists (it's not garbage collected) so does the self-invoking anonymous function along with its state at the time of assignment. This makes any capabilities added to be persistent.

这篇关于JavaScript设计模式需要帮助:模块扩展松散的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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