javascript - "this" in global functions -


i under impression "this" keyword represents current owner in scope. obviously, wrong. let me code:

alert(this);     // alerts [object window] -- okay  function p1() {     alert(this); }  var p2 = function() {     alert(this); }  p1();           // alerts undefined  -- ??? p2();           // alerts undefined  -- ?? window.p1();    // alerts [object window] -- okay window.p2();    // alerts [object window] -- okay 

the code above first alerts [object window], expect next 2 calls p1() , p2() alert "this" "undefined". final 2 calls p1() , p2() alert "this" [object window].

isn't case p1() , p2() exist in global (i.e., window) scope? thought calling window.p1() synonymous calling p1(), calling alert() synonymous window.alert().

to (c#) way of thinking, p1() , p2() in global scope. these functions members of global window object when refer "this" should referring [object window]. obviously, i'm wrong here.

becasue using strict mode , per spec:

if evaluated within strict mode code, value not coerced object.

the code have does alert window in instances of alert, because in strict mode, undefined (as should be)

update: chrome dev tools alerts window not undefined, if wrap in self executing function undefined expected

(function(){    'use strict';    alert(this); }()); 

Comments