I'm using a Modular Pattern in JavaScript. I wonder if we can prevent the public modules to be overridden. For example, in the code below function1, function2, function3 and function4 can be accessed outside but I don't want to override. If these functions are overridden then I want the compiler to generate an error message
"use strict";
var $ = (function(){
return{
function1 : function(){
alert("this is Function1");
},
function2 : function(){
alert("this is Function2");
},
function3 : function(){
alert("this is Function3");
},
function4 : function(){
alert("this is Function4");
}
};
}());
$.function1(); //will alert - this is Function1
$.function2(); //will alert - this is Function2
/*
I don't want to do this, If I do, then I want the compiler to generate an
error message
*/
$.function3=function(){
alert('function 3 is overridden');
};
$.function3(); //will alert - function 3 is overridden
Introduction. It is true that JavaScript supports overriding, not overloading. When you define multiple functions that have the same name, the last one defined will override all the previously defined ones and every time when you invoke a function, the last defined one will get executed.
JavaScript does not support overloading. JavaScript supports overriding, so if you define two functions with the same name, the last one defined will override the previously defined version and every time a call will be made to the function, the last defined one will get executed.
Method Overriding is an OOPs concept closely knit with inheritance. When a child class method overrides the parent class method of the same name, parameters and return type, it is termed as method overriding.
You can use Object.freeze(obj)
to set the entire returned object to be immutable. Additionally, note that you can use const
instead of var
to avoid the object being reassigned.
'use strict';
const $ = (function() {
return Object.freeze({
function1: function() {
alert('this is Function1');
},
function2: function() {
alert('this is Function2');
},
function3: function() {
alert('this is Function3');
},
function4: function() {
alert('this is Function4');
}
});
})();
$.function1(); //will alert - this is Function1
$.function2(); //will alert - this is Function2
// This will now error
$.function3 = function() {
alert('function 3 is overridden');
};
$.function3(); // will not run
Using Object.defineProperty
you can declare the property as read-only.
// Make sure an error is thrown when attempting to overwrite it
// Without strict-mode, re-assigning will fail silently
'use strict';
var API = {};
Object.defineProperty(API, 'function1', {
writable: false,
value: function() {
console.log('Called function1');
}
});
API.function1();
API.function1 = null;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With