Learn about Constructor Function in JavaScript

0
1705
Constructors-470X296

Constructors-470X296

Constructor functions is something that can be used to create multiple different objects of the same type. Basically, constructor provides the functionality that class provides in other object oriented programming languages.

You start writing a constructor with the word function followed by the object’s name, and optionally the parameters you’d like it to receive. Let’s write an example constructor function that creates a Cat object.

We can also include a function inside a constructor function, like so:

We can now create an instance of Cat like so:

cat1 is a new Cat object. The output for:

would be:
1

We can check if a particular object is an instance of a certain object type by using instanceof, Like so:

Output:
2

https://blogeduonix-2f3a.kxcdn.com/wp-content/uploads/2015/10/Learn-Javascript-And-JQuery-From-Scratch.png

We can also pass an object to a function and change its values, like so:

Now we’ll call the new function on cat1:

3

Every function has a prototype property that contains an object. It’s possible to add properties and methods to the prototype object that you can then call on to execute as if they were belonged directly to your object. On our next lesson, we’ll take a look at the subject of inheritance in the context of constructor functions and prototype properties.

LEAVE A REPLY

Please enter your comment!
Please enter your name here