问题描述
我需要一种防止window.location.replace()
被更改/覆盖的方法(例如:window.location.replace = function(){ return "Hi" }
。起初,我尝试了Object.freeze(window.location.replace)
,但是它什么也没做。
解决方法
您可以使用Object.defineProperty
将其设置为不可写和不可配置:
'use strict';
Object.defineProperty(
window.location,'replace',{ value: window.location.replace }
);
// Throws in strict mode
window.location.replace = function(){ return "Hi" };
// In sloppy mode,the above assignment will fail silently
,
这里有2件事:
_ strict mode
:允许Object.freeze
防止对象被编辑。没有“严格模式”,Object.freeze
只能阻止添加,删除。
_ Object.free
只能在对象中生效1级。
解决方案是:
'use strict';
Object.freeze(window.location);