防止覆盖Javascript函数

gre*_*ese 5 javascript

我在JavaScript中使用模块化模式.我想知道我们是否可以阻止公共模块被覆盖.例如,在function1下面的代码中,function2,function3和function4可以在外面访问,但我不想覆盖.如果重写这些函数,那么我希望编译器生成错误消息

"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
Run Code Online (Sandbox Code Playgroud)

Mik*_*uck 8

使用Object.defineProperty您可以将属性声明为只读.

// 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 Code Online (Sandbox Code Playgroud)


BDa*_*awg 8

您可以使用Object.freeze(obj)将整个返回的对象设置为不可变.此外,请注意您可以使用const而不是var避免重新分配对象.

'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
Run Code Online (Sandbox Code Playgroud)