当前位置:  开发笔记 > 编程语言 > 正文

防止覆盖Javascript函数

如何解决《防止覆盖Javascript函数》经验,为你挑选了2个好方法。

我在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

Mike Cluck.. 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;



1> Mike Cluck..:

使用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;


2> BDawg..:

您可以使用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
推荐阅读
大大炮
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有