0

In the following code example:

'use strict';
function hello(name) {
    console.log(this); 
}
hello('Annie');
// undefined

let o = {
    hello() {console.log(this);}
}
o.hello('Annie');

Why does a function have no this context when it's placed by itself, but it does when it is placed within an object?

David542
  • 104,438
  • 178
  • 489
  • 842
  • In strict mode, top-level functions have no context. In non-strict mode the context is the `window` object. – Barmar Mar 24 '22 at 20:25
  • What were you expecting the context to be for the top-level function? – Barmar Mar 24 '22 at 20:26
  • I think it was decided that `this` isn't actually useful, or worse, the source of bugs, when a function is called "normally". Hence strict mode makes it so that `this` is `undefined`. – Felix Kling Mar 24 '22 at 20:29

0 Answers0