JavaScript에서 Revealing 모듈 패턴을 사용하는 방법
이 게시물을 우연히 발견했습니다 : JavaScript의 Revealing Module Pattern . 내 프로젝트에서 이것을 사용하고 싶습니다.
내가 abc
함수가 있고 기본 JavaScript 파일에서 해당 함수를 호출 한다고 가정 해 보겠습니다 .
이 패턴이 상황을 다르게 만들까요? 누구든지이 패턴의 기본 예를 보여줄 수 있습니까?
작은 예 :
var revealed = function(){
var a = [1,2,3];
function abc(){
return (a[0]*a[1])+a[2];
}
return {
name: 'revealed',
abcfn: abc
}
}();
익명 함수 즉, 수득 개시 revealed
값, a
및 abc
그 기능에 전용이다. 어떤 함수가 반환하는 것은와 객체 리터럴 name
속성과 abcfn
받는 사람에 대한 참조입니다 재산 abc function
. 는 abc function
민간 변수를 사용합니다 a
. 이 모든 작업은 클로저를 사용 하여 수행 할 수 있습니다 (함수 범위 내의 모든 것은 동일한 함수의 다른 모든 것에 의해 참조 될 수 있음).
공개 된 사용법 :
alert(revealed.name); //=> 'revealed'
alert(revealed.abcfn()); //=> 5 (1*2+3)
DC = Douglas Crockford
RMP = 모듈 패턴 공개
DC와 RMP의 차이점은 주로 조직적이고 읽을 수 있습니다.
기사 자체에 예가 나와 있습니까? 그리고 정확히 무엇을 요구하고 있는가? 왜냐하면 그것들은 파일이 아니라 클로저와 관련이 있기 때문입니다.
모든 것을 클로저 (함수)에 넣고 접근하기를 원하는 부분 만 노출합니다. DC 스타일과 RMP의 차이는 RMP에 그들은 항상 같은 장소에서 정의하고 다음 나중에 동안 첫 번째 기능에 다른 장소에 정의되어 있다는 것입니다 밝혀 에 공공 객체 리터럴.
따라서 DC 및 RMP에는 다음이 있습니다.
- 비공개 부분 (변수 및 함수)을 정의 할 수있는 클로저
- 사적인 부분
- 공개적으로 표시되는 기능 및 변수 (상태)를 정의하는 공개 결과
이 두 패턴은 가독성 만 다릅니다. DC의 경우 특정 기능이 정의 될 위치를 항상 알 수는 없지만 RMP에서는 항상 모든 것이 비공개 부분에 있음을 알고 있습니다.
공개 모듈 패턴은 초보자를위한 필수 자바 스크립트 디자인 패턴 문서에 잘 설명되어 있습니다.
저자가 호출 한 "Douglas Crockford의 객체 생성 패턴"이라는 방법은 실제로 Richard Cornford 등이 주로 개발 한 모듈 패턴입니다 . http://groups.google.com/group/comp.lang.javascript/msg/9f58bd11bd67d937을 참조하세요.
예를 들어, 많이 있습니다. 다음 기사를 읽고 일부 링크를 따르십시오. http://peter.michaux.ca/articles/module-pattern-provides-no-privacy-at-least-not-in-javascript-tm
모듈 패턴 의 이점으로 구조화 된 코드를 유지할 수 있도록 공개 모듈 패턴 과 싱글 톤 패턴을 혼합하여 사용하고 싶습니다 .
var MyFunction = function(){
var _ = {
Init: function(){
_.Config.foo = "hello world";
},
Config:{
foo:null
},
ShowAlert:function(){
alert(_.Config.foo);
}
}
return {
Init: _.Init,
ShowAlert: _.ShowAlert
};
}();
MyFunction.Init();
MyFunction.ShowAlert();
내 블로그에 이에 대한 자세한 정보를 썼습니다.
http://curtistimson.co.uk/js/mixing-revealing-module-and-singleton-javascript-patterns/
모듈 외부의 코드에는 별 차이가 없습니다. 이 기사의 세 가지 경우 모두 메서드가 동일한 방식으로 호출됩니다. 그러나 모듈 자체의 구조는 내부적으로 다릅니다.
Crockford의 모듈 패턴과 그들이 "공개 모듈 패턴"이라고 부르는 것은 구조적으로 거의 동일합니다. 유일한 차이점은 가독성을 높이기 위해 먼저 로컬 var에 메서드를 할당한다는 것입니다. 그러나 그것에 대해 특별한 것은 없으며 링크에 몇 가지 예가 있습니다.
Revealing Module의 기본 개념은 데이터와 동작 Object
을 캡슐화 하는를 가지고 있다는 것입니다 .
var Module = (function(){
var privateStuff = {};
var publicStuff = {};
return publicStuff;
})();
그러나이 패턴을 사용할 때 사용해야하는 몇 가지 모범 사례가 있습니다. 다음 Modulus
은 데모를위한 몇 가지 속성 이있는 모듈 ( " ")입니다. 이러한 방법 중 일부를 사용합니다.
function AbstractSomeClass(id) {
this.id = id;
return this;
}
var Modulus = (new (function SomeClass() {
var thus = this;
function NameClass(name){
this.value = thus.name || name;
}
AbstractSomeClass.call(this, 998);
this.name = 'Touring';
this.name = ( new NameClass('Hofstadter') ).value;
return {
id: this.id,
name: this.name
};
})());
Notice the (new (function SomeClass(){ ... })());
syntax. Using new
like this allows you to use the this
keyword inside of the closure. This is handy if you need to inherit properties from another class (AbstractSomeClass.call(this, 998);
) -- However, you'll still need to reveal the properties that you would like to have public, e.g.:
return {
id: this.id,
name: this.name
};
Also notice that we assign this
to thus
-- which allows us to use the Parent-this
inside of a subclass that has its own this
scope (this.value = thus.name || name;
)
Once again, these are just a few of the conventions and best practices that are suggested.
Here is the small example of revealing module pattern.
It provides a facility to declare private and public functions just like a class.It is the major benefits of this patterns.If we do not want to expose some of the functionality accessible from globally then makes it private and rest of the make public.Below is the example how to make private and public functions.And one more things it is a self-executable block of code.
var Calculator = (function () {
var num1 = 10;
var num2=5
var _abc = function () {
return num1 - num2;
};
var _mulFunc = function () {
return num1 * num2;
};
var _divFunc = function () {
return num1/num2;
};
return {
//public scope
abc: _abc,
mulFunc:_mulFunc
};
})();
alert(Calculator.abc()); it returns 5
alert(Calculator.mulFunc()); it returns 50
And __divFunc() will not be accessible as it is in private scope. We can access only those functions which is declared inside return object as it is public function representation
Just want to add: with this pattern it's good to pass global dependencies as arguments/params so that they are explicit. You don't have to do it but this makes it very clear what your module needs from the first glance. E.g.:
var myModule = (function ($, loadModule) {
"use strict";
})(jQuery, load);
In this example, you can see right away in the 1st line that you module uses jQuery and some other module responsible for loading functionality.
참고URL : https://stackoverflow.com/questions/5647258/how-to-use-revealing-module-pattern-in-javascript
'development' 카테고리의 다른 글
속성 파일을 사용하여 Java 로깅을 설정하는 방법은 무엇입니까? (0) | 2020.10.12 |
---|---|
HTML : 새 창이 아닌 새 탭에서 링크를 강제로 열도록하는 방법 (0) | 2020.10.12 |
Java의 추상 클래스 대 인터페이스 (0) | 2020.10.12 |
'const std :: vector 초기화 방법 (0) | 2020.10.12 |
Objective-C 검사 / 반사 (0) | 2020.10.12 |