JavaScript模块模式与示例 [英] JavaScript module pattern with example

查看:141
本文介绍了JavaScript模块模式与示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找不到任何可访问的示例,显示两个(或更多)不同的模块如何连接在一起工作。

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.

推荐答案

为了接近模块化设计模式,你需要首先理解这些概念:

In order to approach to Modular design pattern, you need to understand these concept first:

立即调用函数表达式(IIFE):

Immediately-Invoked Function Expression (IIFE):

(function() {
      // Your code goes here 
}());

有两种方法可以使用这些功能。 1.功能声明2.功能定义。
这里使用函数定义表达式。

There are two ways you can use the functions. 1. Function declaration 2. Function definition. Here are using function definition expression.

什么是命名空间?
现在,如果我们将命名空间添加到上面的代码中,那么

What is namespace? Now if we add the namespace to the above piece of code then

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

JS中的闭包是什么?

What is closure in JS?

这意味着如果我们在另一个函数内部声明任何变量scope /的任何函数(在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.

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

jsfiddle。

目标是隐藏来自外部世界的变量可访问性。

The objective is to hide the variable accessibility from the outside world.

希望这会有所帮助。祝你好运。

Hope this helps. Good Luck.

这篇关于JavaScript模块模式与示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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