Module Pattern: Restrict a module from being extended

时间:2016-08-31 17:16:55

标签: javascript design-patterns module-pattern revealing-module-pattern

I've been reading several articles on Design Patterns in Javascript. I found module pattern easy to read/write.

I'm wondering if there is any way to stop extending a module in Javascript.

Here is the script that I've been working with:

var MODULE = (function(){
    var increment = 0;

    var funcIncrement = function(){
        increment ++;
        console.log(increment);
    };

    return {
        incr: funcIncrement
    }
})();


var moduleTwo = (function(MODULE){
    MODULE.extension = function(){ //This module will add extension function to MODULE. I don't want this to happen
        console.log('extension method');
    }


})(MODULE || {});

If I do console.log(MODULE) after running those the above snippet, then I'll get two function for MODULE (incr, extension)

Is there a way to restrict the MODULE from being extended when declaring the MODULE for the first time ?

1 个答案:

答案 0 :(得分:3)

You can freeze returned object

var MODULE = (function(){
  var increment = 0;

  var funcIncrement = function(){
    increment ++;
    console.log(increment);
  };

  return Object.freeze({
    incr: funcIncrement
  });
})();

But it is not supported in older browsers.