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()
or ...
Get Object-Oriented JavaScript - Third Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.