In JavaScript, there are no special constructor functions. Instead, a function call can turn into a constructor call when that function is called with the new
operator in front of it.
When a function is called as a constructor, a new object is created and set as the function's this
argument. This object is then returned implicitly from the function if no other object is returned explicitly.
In this lesson, we'll play around with constructor calls and see why it might make sense to return a different object from the function.
Instructor: [00:00] In JavaScript, a function call with a new operator in front of it turns into a constructor call. When a function is invoked as a constructor, a brand-new object is created for us automatically, and that new object is then used as the this binding for the function call.
[00:17] In our example, we are initializing the new object by setting the two properties first name and last name. If I put in a couple of log statements, we can trace how the person object is put together step by step. We also see the name of the constructor function in notes console output.
[00:39] This shows us that our new object has been linked to the person function's prototype. Notice that our person function doesn't contain a return statement. In that case, the brand-new object that was constructed for us is returned automatically.
[01:02] You can imagine an invisible return this statement at the end of the function. We can also return an entirely different object from the constructor function. After we return from the function, the newly-created object that we previously initialized is lost because it's out of scope and nobody has a reference to it anymore.
[01:33] It's not a very common use case to return a different object from its constructor function, but it might make sense in certain scenarios. For example, in a development environment, we could wrap the returned object in a proxy and alert developers whenever they use that object incorrectly.
[01:48] Note that if we try to return anything else than an object, the JavaScript engine will simply ignore the value we provided and return the newly-created object instead. This is why we see Jane Doe printed to the console, although we tried to return null.