Posts

Showing posts from June, 2014

JavaScript singleton pattern

In JavaScript,  it would let you feel struggle to implement singleton design pattern. This is my first experiment: View = { _viewer: undefined, initView: function() { // init view }, getView: function() { // get view return _viewer; } }; But I figure out this approach can't express 'encapsulate', so the user can get _viewer directly. Therefore, I decide to rewrite it. I rewrite it to: var View = ( function() { var _viewer = undefined; function init() { // init view }; function getView() { // get view return _viewer; }; return { init(): { init(); }, getView(): { return getView(); } }; }; } ) (); This method can achieve 'encapsulate', uses its method like View.getView(), but you have to program the interface two times on function and return pa