Loading [MathJax]/jax/output/HTML-CSS/fonts/TeX/fontdata.js

The NEW keyword constrcutor

In the last example we saw that we had three objects that shared exactly the same keys, maybe not the same values, but they keys where the same! In such cases and instead of creating and initializing a new object by creating the same structure again and again, we can create an object constructor.

An object constructor is a function that constructs objects given a designated schema. It's NOT an object, but a blueprint and every object that is created by this constructor will have this shape and these properties. Then the values can be parameterized exactly the same way we parameterize arguments in functions!

Take a close look to the example above. We want to create many objects for people and we want to store the same piece of info there. Firstname, lastname and age. Then we can create a constructor that accepts three arguments. These arguments will be the values that will fill the properties for each object separately. On the left side we define the name of the properties. This can be anything but it's always good to be as descriptive as possible. 

Then we create two objects from this constructor. In order to do this we use the NEW keyword which means that we create a new object from a specific constructor function. Thus we have created a re-usable way to instantiate objects! If a specific property has a fixed value, then instead of an argument we can put the fix value to this property.

For example after line 23 we could add another property for every object that will be created from this constructor like:

this.profession = 'student'

Then both objects now have the profession property set as student. We don't need to put another argument because the value is fixed and not parameterized. It doesn't differ in other words from object  to object.

O-3 Use a constructor for the previous exercise so you don't have to create an object literal from the beginning every time. Use arguments where you have to parameterize the values of the properties and fixed values where needed!

New Constructor

Kostas Diakogiannis
Module by Kostas Diakogiannis, updated more than 1 year ago
No tags specified