The Complete Rules to `new`
The 'new' keyword is a central part of object-oriented programming in JavaScript. This lesson will discuss how it turns a normal function into a constructor. We'll cover all of the logic that the engine inserts into our function calls when we use 'new' and how it helps us write powerful code.
We'll cover the following...
Javascript’s “new” Keyword Explained as Simply as Possible
Normal Function Call
To explain what new
does, let’s start with just a normal function, called without new
. We want to write a function that will create “person
” objects. It’ll give these objects name
and age
properties based on parameters that it takes in.
function personFn(name, age) {const personObj = {};personObj.name = name;personObj.age = age;return personObj;}const alex = personFn('Alex', 30);console.log(alex); // -> { name: 'Alex', age: 30 }
Simple enough. We create an object, add the properties to it, and return it at the end.
new
Let’s create a function that does the same thing, but we want it to be invoked using new
. This function will create the same object as the one above. Common practice is to make functions that are meant to be invoked with new
start with a capital letter. These functions are also referred to as constructors.
function PersonConstructor(name, age) {this.name = name;this.age = age;}const christa = new PersonConstructor('Christa', 30);console.log(christa); // -> { name: 'Christa', age: 30 }
Invoking personFn
normally and invoking ...