如何在JavaScript中使用Revealing模块模式 [英] How to use Revealing module pattern in JavaScript

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

问题描述

我偶然发现了这篇文章: JavaScript的揭示模块模式 。我想在我的项目中使用它。

I stumbled across this post: JavaScript's Revealing Module Pattern. I would like to use this in my project.

假设我有一个函数 abc ,我在我的主JavaScript文件中调用该函数。

Let's imagine I have a function abc and I am calling that function in my main JavaScript file.

这种模式会有什么不同吗?有人能告诉我这个模式的一个基本例子吗?

Does this pattern make things different? Can anyone show me a basic example of this pattern?

推荐答案

一个小例子:

var revealed = function(){
   var a = [1,2,3];
   function abc(){
     return (a[0]*a[1])+a[2];
   }

   return {
      name: 'revealed',
      abcfn: abc
   }
}();

在匿名函数中启动以显示 一个值, a abc 是该函数的私有值。函数返回的是具有 name 属性的对象文字和<$​​ c $ c> abcfn 属性,它是对<的引用code> abc函数。 abc函数使用私有变量 a 。由于使用了闭包(功能范围内的所有内容),所有这一切都可以完成可以被同一函数中的其他所有内容引用。)

in the anonymous function that is initiated to give revealed a value, a and abc are private to that function. What the function returns is an object literal with a name property and a abcfn property, which is a reference to the abc function. The abc function uses the private variable a. This can all be done thanks to the use of closures (everything within the scope of a function can be referenced by everything else in that same function).

显示用法:

alert(revealed.name);    //=> 'revealed'
alert(revealed.abcfn()); //=> 5 (1*2+3)

这篇关于如何在JavaScript中使用Revealing模块模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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