Prevent Javascript Function Overrides

I am using a modular template in JavaScript. I wonder if we can prevent the redefinition of publicly available modules. For example, in the code below, function1, function2, function3 and function4 can be accessed from the outside, but I do not want to override. If these functions are overridden, 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
+4
source share
3 answers

You can use the Object.freeze(obj)whole returned object to be immutable.

'use strict';

var $ = (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
Run codeHide result
+6
source

Using Object.defineProperty, you can declare a 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', {
  writeable: false,
  value: function() {
    console.log('Called function1');
  }
});

API.function1();
API.function1 = null;
Run codeHide result
+7
source

, Object.defineProperty. false.

:

var $ = (function(){

var newObject = {};

Object.defineProperty (newObject, "function1", {value: function() {  alert("this is Function1");}, writable:false, configurable:false)});

// etc.

return object;
}());

, , , false, function1 . , JavaScript Function, : false. , , 1 .

, Object.freeze. , .

+3
source

Source: https://habr.com/ru/post/1666736/


All Articles