Object Constructor:
We saw how to create an object on the last page, but in life, nothing stands still. Our first piece of code mentioned my favourite car, the Aston Martin V8 Vantage. But there is a new model and the details within the code need to be updated.
And what if the Dogs d'Amour reformed, hired a different guitarit? Again, the code would need to be updated.
For our code here, it would perhaps be easy to do that by copying inside of the code. But what if you have an object with
hundreds of key / data properties?
Not onlt would it be tedious and time consuming to update all that code manually, as humans we are prone to mistakes and there is
a high probability that we might miss a data value to insert.
This is where the constructor function comes in useful:
Notice that:
- Name of function:
- Function parameters
this.key = key;:- The
function expression:
Because it is a constructor function, its name starts with a capital letter.
On the last page, we listed the key / data values within the Object. The constructor function
is pretending to be an Object. Its "keys"" are the function parameters.
We do not list the data values inside the function. Instead, we will call and assign them
in a new instance of the Function. Also, unlike with Objects, each key ends with ;.
This is not listed within the parameters of the Function.
We declare and name our variable, then assign new to it, and then call our constructor function:
We have also done the same with the link.
The this.url = url becomes
new instance:Our new Band(), being the variable dogsDamour is called thus:
(We called it in this instance using document.getElementById("#").innerText = dogsDamour.name in order to display it below.)
But note that when we call the alert, we are calling the function expression, thus we use dogsDamour.alert().
Let's see the result: