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

In many compiled Javascript modules, somewhere in the preamble there is a call to Function('return this')()to get a global object. I work in an interpreter environment where the use of a constructor Function(together with eval) is prohibited for security reasons. I replaced the above code with (function(){return this})(), and everything seems to work.

Is this a safe replacement? Are there any cases where this may fail? Why do most compiled JS modules prefer a constructor anyway?

+4
source share
2 answers

In strict mode, you are not getting a global object; instead you get undefined:

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

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

Function , , :

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

console.log( window === function(){
  "use strict";
  return Function('return this')();
}() ); // true
Hide result
+3

Function('return this')() , this .

(function(){return this})() .

0

Source: https://habr.com/ru/post/1695180/


All Articles