简体   繁体   中英

Can I protect native JavaScript functions

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?

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 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM