猿问

如何防止“window.location.replace()”被覆盖?

我需要一种方法来防止window.location.replace()被更改/覆盖(例如:window.location.replace = function(){ return "Hi" }。起初,我尝试过Object.freeze(window.location.replace)但这没有做任何事情。



一只斗牛犬
浏览 238回答 2
2回答

慕的地8271018

您可以使用Object.defineProperty使其不可写和不可配置:'use strict';Object.defineProperty(  window.location,  'replace',  { value: window.location.replace });// Throws in strict modewindow.location.replace = function(){ return "Hi" };// In sloppy mode, the above assignment will fail silently

慕田峪4524236

这里有两件事:_ strict mode:允许Object.freeze防止对象被编辑。没有'严格模式',Object.freeze只能防止添加,删除。_Object.free只能对对象中的 1 层生效。所以解决方案是:'use strict'; Object.freeze(window.location);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答