我需要一种方法来防止console.log()
被更改/覆盖(例如: console.log = function(){ return "Hi" }
。起初,我尝试了Object.freeze(console.log)
但这并没有做任何事情。
You can freeze the object console instead of the attribute. Object.freeze(console)
You can use Object.defineProperty
to make the property non-writable and non-configurable:
Object.defineProperty(console, 'log', { value: console.log, writable: false, configurable: false }); // Below won't work now, and will throw in strict mode: console.log = () => null; console.log('foobar');
You may also wish to make window.console
non-overwritable as well:
Object.defineProperty(console, 'log', { value: console.log, writable: false, configurable: false }); Object.defineProperty(window, 'console', { value: console, writable: false, configurable: false }); // Below won't work now, and will throw in strict mode: console.log = () => null; // Below won't work either: window.console = { dir: () => null }; console.log('foobar'); console.log('barbaz');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.