我可以保护原生JavaScript函数吗 [英] Can I protect native JavaScript functions
问题描述
有什么方法可以防止用户覆盖本机功能?
Is there any way to prevent a user from overriding a native function?
示例:
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 :(
有什么方法可以防止本机函数被覆盖?也许使用CSP或密封对象...这甚至可能吗?
Is there any way to prevent native functions from being overridden? Maybe with CSP or sealing the Object... is this even possible?
推荐答案
实际上,您可以使用 Object.freeze(Math)
:
In fact, you can use Object.freeze(Math)
:
Object.freeze()方法冻结一个对象:即,防止新 从属性添加到它;防止现有属性 被删除;并防止现有财产或其 可更改性,可配置性或可写性.在 本质上,对象实际上是不可变的.方法返回 被冻结的对象.
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 可能需要向Math
添加函数或其他功能,但正如我之前所说的那样,冻结内置对象时可能只是一个问题...).
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...).
...使用Object.defineProperty(...)
修改现有的属性描述符:
...using Object.defineProperty(...)
to modify an existing property descriptor:
Object.defineProperty(Math, "random", {
configurable: false,
writable: false
});
这篇关于我可以保护原生JavaScript函数吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!