带有示例的 JavaScript 模块模式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17776940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript module pattern with example
提问by Srle
I can't find any accessible examples showing how two (or more) different modules are connected to work together.
我找不到任何显示两个(或更多)不同模块如何连接在一起工作的可访问示例。
So, I'd like to ask whether anyone has time to write an example explaining how modules work together.
所以,我想问一下是否有人有时间写一个例子来解释模块如何协同工作。
回答by kta
In order to approach to Modular design pattern, you need to understand these concept first:
为了接近模块化设计模式,您需要首先了解这些概念:
Immediately-Invoked Function Expression (IIFE):
立即调用函数表达式 (IIFE):
(function() {
// Your code goes here
}());
There are two ways you can use the functions. 1. Function declaration 2. Function expression.
您可以通过两种方式使用这些功能。1. 函数声明 2. 函数表达式。
Here are using function expression.
这里使用函数表达式。
What is namespace? Now if we add the namespace to the above piece of code then
什么是命名空间?现在,如果我们将命名空间添加到上面的代码中,那么
var anoyn = (function() {
}());
What is closure in JS?
JS 中的闭包是什么?
It means if we declare any function with any variable scope/inside another function (in JS we can declare a function inside another function!) then it will count that function scope always. This means that any variable in outer function will be read always. It will not read the global variable (if any) with the same name. This is also one of the objective of using modular design pattern avoiding naming conflict.
这意味着如果我们声明任何具有任何变量作用域/在另一个函数内部的函数(在 JS 中我们可以在另一个函数内部声明一个函数!)那么它将始终计算该函数作用域。这意味着将始终读取外部函数中的任何变量。它不会读取同名的全局变量(如果有)。这也是使用模块化设计模式避免命名冲突的目的之一。
var scope = "I am global";
function whatismyscope() {
var scope = "I am just a local";
function func() {return scope;}
return func;
}
whatismyscope()()
Now we will apply these three concepts I mentioned above to define our first modular design pattern:
现在我们将应用我上面提到的这三个概念来定义我们的第一个模块化设计模式:
var modularpattern = (function() {
// your module code goes here
var sum = 0 ;
return {
add:function() {
sum = sum + 1;
return sum;
},
reset:function() {
return sum = 0;
}
}
}());
alert(modularpattern.add()); // alerts: 1
alert(modularpattern.add()); // alerts: 2
alert(modularpattern.reset()); // alerts: 0
The objective is to hide the variable accessibility from the outside world.
目标是对外界隐藏可变的可访问性。
Hope this helps. Good Luck.
希望这可以帮助。祝你好运。
回答by Code Novitiate
I would really recommend anyone entering this subject to read Addy Osmani's free book:
我真的建议任何进入这个主题的人阅读 Addy Osmani 的免费书:
"Learning JavaScript Design Patterns".
“学习 JavaScript 设计模式”。
http://addyosmani.com/resources/essentialjsdesignpatterns/book/
http://addyosmani.com/resources/essentialjsdesignpatterns/book/
This book helped me out immensely when I was starting into writing more maintainable JavaScript and I still use it as a reference. Have a look at his different module pattern implementations, he explains them really well.
当我开始编写更易于维护的 JavaScript 并且我仍然将其用作参考时,这本书极大地帮助了我。看看他不同的模块模式实现,他很好地解释了它们。
回答by JonnyRaa
I thought i'd expand on the above answer by talking about how you'd fit modules together into an application. I'd read about this in the doug crockford book but being new to javascript it was all still a bit mysterious.
我想我会通过讨论如何将模块组合到应用程序中来扩展上述答案。我在 doug crockford 的书中读到了这方面的内容,但作为 JavaScript 新手,这一切仍然有点神秘。
I come from a c# background so have added some terminology I find useful from there.
我来自 ac# 背景,所以添加了一些我觉得有用的术语。
Html
html
You'll have some kindof top level html file. It helps to think of this as your project file. Every javascript file you add to the project wants to go into this, unfortunately you dont get tool support for this (I'm using IDEA).
您将拥有某种顶级 html 文件。将其视为您的项目文件会有所帮助。您添加到项目中的每个 javascript 文件都想参与其中,不幸的是,您没有获得对此的工具支持(我使用的是 IDEA)。
You need add files to the project with script tags like this:
您需要使用脚本标记将文件添加到项目中,如下所示:
<script type="text/javascript" src="app/native/MasterFile.js" /></script>
<script type="text/javascript" src="app/native/SomeComponent.js" /></script>
It appears collapsing the tags causes things to fail - whilst it looks like xml it's really something with crazier rules!
似乎折叠标签会导致事情失败 - 虽然它看起来像 xml,但它确实有更疯狂的规则!
Namespace file
命名空间文件
MasterFile.js
主文件.js
myAppNamespace = {};
that's it. This is just for adding a single global variable for the rest of our code to live in. You could also declare nested namespaces here (or in their own files).
而已。这只是为我们的其余代码添加一个全局变量。您也可以在此处(或在它们自己的文件中)声明嵌套命名空间。
Module(s)
模块
SomeComponent.js
一些组件.js
myAppNamespace.messageCounter= (function(){
var privateState = 0;
var incrementCount = function () {
privateState += 1;
};
return function (message) {
incrementCount();
//TODO something with the message!
}
})();
What we're doing here is assigning a message counter function to a variable in our application. It's a function which returns a function which we immediately execute.
我们在这里所做的是将一个消息计数器函数分配给我们应用程序中的一个变量。这是一个函数,它返回一个我们立即执行的函数。
Concepts
概念
I think it helps to think of the top line in SomeComponent as being the namespace where you are declaring something. The only caveat to this is all your namespaces need to appear in some other file first - they are just objects rooted by our application variable.
我认为将 SomeComponent 中的第一行视为您声明某些内容的命名空间会有所帮助。唯一需要注意的是,所有命名空间都需要首先出现在其他文件中——它们只是以我们的应用程序变量为根的对象。
I've only taken minor steps with this at the moment (i'm refactoring some normal javascript out of an extjs app so I can test it) but it seems quite nice as you can define little functional units whilst avoiding the quagmire of 'this'.
目前我只采取了一些小步骤(我正在从 extjs 应用程序中重构一些普通的 javascript,以便我可以测试它)但是它看起来非常好,因为您可以定义小的功能单元同时避免“这个”的泥潭'.
You can also use this style to define constructors by returning a function which returns an object with a collection of functions and not calling it immediately.
您还可以使用这种风格来定义构造函数,方法是返回一个函数,该函数返回一个带有函数集合的对象,而不是立即调用它。
回答by Dmitry Sheiko
Here https://toddmotto.com/mastering-the-module-patternyou can find the pattern thoroughly explained. I would add that the second thing about modular JavaScript is how to structure your code in multiple files. Many folks may advice you here to go with AMD, yet I can say from experience that you will end up on some point with slow page response because of numerous HTTP requests. The way out is pre-compilation of your JavaScript modules (one per file) into a single file following CommonJS standard. Take a look at samples here http://dsheiko.github.io/cjsc/
在这里https://toddmotto.com/mastering-the-module-pattern您可以找到彻底解释的模式。我想补充一点,关于模块化 JavaScript 的第二件事是如何在多个文件中构建代码。很多人可能会在这里建议您使用 AMD,但我可以根据经验说,由于大量 HTTP 请求,您最终会在某些时候页面响应缓慢。出路是按照 CommonJS 标准将 JavaScript 模块(每个文件一个)预编译为单个文件。在此处查看示例http://dsheiko.github.io/cjsc/
回答by Roman
You can find Module Pattern JavaScript here http://www.sga.su/module-pattern-javascript/
你可以在这里找到模块模式 JavaScript http://www.sga.su/module-pattern-javascript/