0

Bellow code example is normal function in strict mode and when we call this function browser console show undefined. This is normal.

"use strict";
function checkBinding() {
    console.log(this);
}
checkBinding();

But if we change code like bellow now console show Window object.

"use strict";
var checkBinding = new Function("console.log(this)");
checkBinding();

What is going on there?

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
Murad Sofiyev
  • 790
  • 1
  • 8
  • 25
  • No If second exmaple also add use strict also this value show Window global object. – Murad Sofiyev Aug 23 '19 at 03:14
  • This is not duplicate question. Remove mark for duplicate.@CertainPerformance – Murad Sofiyev Aug 23 '19 at 03:16
  • Oh yeah, I see what you mean. *functions created using the Function constructor don't inherit strict mode from their context, so must have an explicit `"use strict";` statement if you want them in strict mode.* – CertainPerformance Aug 23 '19 at 03:17
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode#Securing_JavaScript – AndTheGodsMadeLove Aug 23 '19 at 03:18
  • Can you send me Ecma Spesification link about this I don't find @CertainPerformance – Murad Sofiyev Aug 23 '19 at 03:19
  • @AndTheGodsMadeLove In MDN don't talk about functions created using the Function constructor – Murad Sofiyev Aug 23 '19 at 03:20
  • See https://www.ecma-international.org/ecma-262/5.1/#sec-10.1.1 - `new Function` is described in the last bullet point. In short, `new Function` will always result in the code inside running in sloppy mode by default, unless the dynamically-created function has `'use strict'` in it – CertainPerformance Aug 23 '19 at 03:21
  • @CertainPerformance Thanks. But why there are don't do this default strict mode? – Murad Sofiyev Aug 23 '19 at 03:25
  • 1
    It might be because strict mode can cause errors instead of silent failures, and some (bad) scripts depend on those silent failures not throwing errors - so, strict mode has to be used deliberately – CertainPerformance Aug 23 '19 at 03:27
  • @CertainPerformance I have question this is interesting for me. new Function feature come from ES1 yeah? – Murad Sofiyev Aug 23 '19 at 04:28
  • But why new Function [[Environment]] always Global Lexical Environment? Is this for optimisaition? – Murad Sofiyev Aug 23 '19 at 04:29

0 Answers0