0

Lets consider a case where I would like to override the require() function but I want it to avoid further redefinition at some point. Consider the following scenario:

// I redefine require here
var _require = require;
require = function(){
   // some code to redefine original require
}
// After this redefinition shouldn't happen

I know that it is possible to "freeze" object's function using Object.freeze(obj) hence I'm not allowed to modify the object after the statement. But I couldn't find the equivalent of Object.freeze() for global/local functions like require.

ebudi
  • 287
  • 2
  • 3
  • You in principle can try to freeze global namespace - `Object.freeze(window)` in browsers. But I am not sure if it will work that way. window namespace object is kind of special. – c-smile Dec 07 '15 at 20:31

1 Answers1

0

You'll want to use

Object.defineProperty(window, "require", {
    // current `value` is used
    writable: false,
    configurable: false
});

And don't forget to hide _require in a closure scope properly.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thanks! How to do this in the context of Node.JS (there's no `window` object in Node.JS), can I use something like `Object.defineProperty(GLOBAL,"require")` ? – ebudi Dec 07 '15 at 20:49
  • Yes, you should be able to use `global`, but I'm not sure whether `require` is actually a global variable in node.js at all. – Bergi Dec 07 '15 at 20:51
  • @ebudi: see [In what scope are module variables stored in node.js?](http://stackoverflow.com/q/15406062/1048572). So you would only be able to redefine `require` in your own modules anyway, and there you hardly will need to prevent redefinitions. – Bergi Dec 07 '15 at 21:01