Skip to content
Advertisement

What is the difference between `Function(‘return this’)` and `function() {return this}`?

In a lot of the compiled Javascript modules, somewhere in the preamble there is an invocation to Function('return this')() to get the global object. I’m working in an interpreter environment where the use of Function constructor (along with eval) is forbidden for security reasons. I replaced the above code with (function(){return this})() and everything seems to be working.

Is this a safe substitution to do? Are there cases where it would fail? Why do most compiled JS modules prefer the constructor version anyway?

Advertisement

Answer

In strict mode you don’t get the global object; you get undefined instead:

console.log( window === function(){
  return (function(){return this})();
}() ); // true

console.log( window === function(){
  "use strict";
  return (function(){return this})();
}() ); // false

The Function constructor escapes strict mode, so that you get the same result regardless of whether you’re already in strict mode:

console.log( window === function(){
  return Function('return this')();
}() ); // true

console.log( window === function(){
  "use strict";
  return Function('return this')();
}() ); // true
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement