Pay attention to the two blocks of code above. Can you see that zell and vincy have the same properties and methods?
We can create a blueprint that spits out firstName and lastName. One way to create this blueprint is to use a constructor.
We can then use the constructor to create humans like zell and vincy. Objects created from blueprints are called instances.
Creating a constructor
A constructor is a function. We begin constructors with a capital letter so we know it’s different from normal functions.
In this case, let’s call the constructor Human.
function Human () {
// ...
}
We can use the this keyword inside a constructor to create properties. The this keyword refers to the instance that’s going to be created later.
function Human (firstName, lastName) {
this.firstName = firstName
this.lastName = lastName
}
Creating an instance
You create an instance by doing two things:
Use the new keyword
Call the constructor function
// Creating an instance
const zell = new Human('Zell', 'Liew')
You can create as many instances as you want. Each instance will retain their individuality.
const zell = new Human('Zell', 'Liew')
const vincy = new Human('Vincy', 'Zhang')
console.log(zell)
console.log(vincy)
Both zell and vincy are instances of Human.
Instances in the wild
You have been creating instances without knowing it.
For example, when you create an array with [], you actually create a new instance of Array. JavaScript simply lets you use [] as a shorthand to new Array()
// These two arrays have an identical structure
const array = ['hello']
const array2 = new Array('hello')
console.log(array)
console.log(array2)
The same applies to Objects. You’ve been creating Objects with {}. But JavaScript uses new Object() behind the scenes.
// These two objects have an identical structure
const object = { property: 'value' }
const object2 = new Object()
object2.property = 'value'
console.log(object)
console.log(object2)
Another example: You can create elements with document.createElement. When you use this method, you actually create a new Element object.
However, you don’t use the new keyword this time round.
const p = document.createElement('p')
Why? Because there are many flavours of Object Oriented Programming! Some of them don’t need new. We’ll dive into these flavours in the next lesson.
Exercise
Create a Human constructor that contains firstName and lastName properties
Create three instances with different names.
Create a sayName method in the constructor. This method should log the instance’s firstName and lastName.