How Does That Work?
Here’s what happens when a function is called with the “new” keyword :-
A call to “new Foo()” creates a new object instance, said to be of type “Foo”.The object instance is assigned a prototype of “Foo.prototype”.The “Foo” function is then invoked with the new object instance assigned to “this” in that function invocation.
The “Foo” object instance is returned from the function call.Since the value of “this” is a new object of a “Foo” type, in this example, the assignment of “this.bar” adds a “bar” attribute to the Foo instance. Logging “this” from the constructor function will log the object in it’s current state (with it’s current attributes and methods). When the constructor function exits, the object instance is assigned to the “f” variable. The “f” variable, pointing to the object instance, then has the “bar” attribute available, which is then logged to the console.
You should know that the “new” keyword changes the behavior of a function. It turns that function in to a constructor function. The value of “this” inside of the constructor function is a new instance of that object type, where the “type” is defined by the constructor function, itself.
The value of “this” is once again determined by the invocation pattern of the function and not by the function definition. Calling “new Foo.Bar.Baz()” will assign an instance of a “Baz” type to “this” inside of the “Baz” function.