有什么方法可以防止用户覆盖原生函数吗?
例子:
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 可能需要向 Math< 添加函数或其他内容
但正如我之前所说,这只是卡住内置对象时可能出现的问题...)。
您还可以卡住个别属性...
...使用 Object.defineProperty(...)
修改现有属性描述符:
Object.defineProperty(Math, "random", {
configurable: false,
writable: false
});
关于javascript - 我可以保护原生 JavaScript 函数吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37532808/