2017-12-02 7 views
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 
    }; 
})(); 

이 두 패턴 중 하나를 사용에 상당한 차이가 날

  1. 에 같은 일을하는 것?
  2. 이러한 패턴 중 하나를 피해야합니까?
  3. 둘 중 하나를 사용하는 더 좋은 방법이 있습니까?
+1

유일한 차이점은 버전 2에서 메소드 자체 대신 메소드 결과를 리턴한다는 것입니다. 그리고 두 번째는 더 짧고 잘 구조화 된 것을 선호합니다. –

+0

es 모듈을 사용할 수도 있다는 것을 명심하십시오. 그러나 –

+0

에 대한 바벨이 필요합니다. 두 번째 스 니펫은 "내보내기"대신 * public * method()를 호출합니다. – Bergi

답변

1

실제로 언급 한 두 패턴 사이에는 차이가 없습니다. 두 번째 패턴은 피할 수있는 추가 변수로 wrapper을 사용한다는 차이점 만 있습니다. 당신이 현재보다는 복잡한 개체를 반환 할 수 있습니다 다른 경우를 고려

, 다음 두 번째 패턴은 매우 유용 예에 대한

.

var wrapper = { 
_privateVariable: '', 

_privateMethod: function() { 
    var _this = this; 
    console.log('Inside a private method!'); 
}, 

publicMethod: function() { 
    var _this = this; 
}, 

publicMethod2: function() { 
    var _this = null; 
}, 

publicMethod3: function(default) { 
    var _this = default; 
}, 
}; 

return { 
    publicMethod: wrapper 
};