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 ?
答案 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.