Chapter 4, Objects

Lets solve the following exercises:

Exercises

  1. What happens here? What is this and what's o?
            function F() { 
              function C() { 
                return this; 
              } 
              return C(); 
            } 
            var o = new F(); 
    

    Here, this === window because C() was called without new.

    Also o === window because new F() returns the object returned by C(), which is this, and this is window.

    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 the C() constructor. So is o:

            > o.constructor.name; 
            "C" 
    

    It becomes more interesting with ES5's strict mode. In the strict mode, non-constructor invocations result in this being undefined, not the global object. With "use strict" inside F() 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.