我可以保护原生 JavaScript 函数吗

Can I protect native JavaScript functions

有什么方法可以防止用户覆盖本机功能吗?

示例:

var getRand;
(function(){
  'use strict';
  getRand = function(){
    return Math.random();
  }
})();

getRand(); //gives a nice random number

页面加载后,在控制台中覆盖。

Math.random = function (){ return 0 };

getRand(); //gives 0 :(

有没有办法防止原生函数被覆盖?也许使用 CSP 或密封对象...这甚至可能吗?

其实可以用Object.freeze(Math):

The Object.freeze() method freezes an object: that is, prevents new properties from being added to it; prevents existing properties from being removed; and prevents existing properties, or their enumerability, configurability, or writability, from being changed. In essence the object is made effectively immutable. The method returns the object being frozen.

Object.freeze(Math);

// This won't work or it won't replace
// the function with the whole string...
Math.random = "hello world"; 

除非任何其他库可能依赖于扩展或修改 Math(例如,可能 polyfill 可能需要向 [=13 添加函数或其他内容=] 但正如我之前所说,这只是冻结内置对象时可能出现的问题...)。

您还可以冻结个别属性...

...使用 Object.defineProperty(...) 修改现有的 属性 描述符:

Object.defineProperty(Math, "random", { 
    configurable: false,
    writable: false 
});