Chapter 4, Objects
Lets solve the following exercises:
Exercises
- What happens here? What is
this
and what'so
?function F() { function C() { return this; } return C(); } var o = new F();
Here,
this === window
becauseC()
was called withoutnew
.Also
o === window
becausenew F()
returns the object returned byC()
, which isthis
, andthis
iswindow
.You can make the call to
C()
a constructor call:function F() { function C() { return this; } return new C(); } var o = new F();
Here,
this
is the object created by theC()
constructor. So iso
:> o.constructor.name; "C"
It becomes more interesting with ES5's strict mode. In the strict mode, non-constructor invocations result in
this
beingundefined
, not the global object. With"use strict"
insideF()
orC()
constructor's body,this
would beundefined
...