0
자바 스크립트 모듈 패턴을 알고 있지만 두 가지 유형의 모듈 패턴을 사용하며 아키텍처 측면에서 차이점을 알고 싶습니다.자바 스크립트 모듈 패턴 - 차이점
// PATTERN ONE
var module = (function() {
var _privateVariable = '';
var _privateMethod = function() {
var _this = this;
// private method def
// can use _this._privateVariable
console.log('Inside a private method!');
};
var publicMethod = function() {
var _this = this;
// public method def
// can use _this._privateVariable
// can call _privateMethod();
};
return {
publicMethod: publicMethod
};
})();
// PATTERN TWO
var module = (function() {
var wrapper = {
_privateVariable: '',
_privateMethod: function() {
var _this = this;
// private method def
// can use _this._privateVariable
console.log('Inside a private method!');
},
publicMethod: function() {
var _this = this;
// public method def
// can use _this._privateVariable
// can call _privateMethod();
},
};
return {
publicMethod: wrapper.publicMethod
};
})();
이 두 패턴 중 하나를 사용에 상당한 차이가 날
- 에 같은 일을하는 것?
- 이러한 패턴 중 하나를 피해야합니까?
- 둘 중 하나를 사용하는 더 좋은 방법이 있습니까?
유일한 차이점은 버전 2에서 메소드 자체 대신 메소드 결과를 리턴한다는 것입니다. 그리고 두 번째는 더 짧고 잘 구조화 된 것을 선호합니다. –
es 모듈을 사용할 수도 있다는 것을 명심하십시오. 그러나 –
에 대한 바벨이 필요합니다. 두 번째 스 니펫은 "내보내기"대신 * public * method()를 호출합니다. – Bergi