Skip to content Skip to sidebar Skip to footer

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

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

Post a Comment for "Can I Protect Native JavaScript Functions"