Can I protect native JavaScript functions

2019-08-03 18:53发布

问题:

Is there any way to prevent a user from overriding a native function?

Example:

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

getRand(); //gives a nice random number

After the page has loaded, overriding in console.

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

getRand(); //gives 0 :(

Is there any way to prevent native functions from being overridden? Maybe with CSP or sealing the Object... is this even possible?

回答1:

In fact, you can use 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"; 

Unless any other library could be relying on extending or modifying Math (for example, maybe a polyfill might need to add a function or whatever to Math but as I said before, it's just a possible issue when freezing a built-in object...).

You can also freeze individual properties...

...using Object.defineProperty(...) to modify an existing property descriptor:

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