Web Programming TutorialsLearn about Constructor Function in JavaScript

Learn about Constructor Function in JavaScript

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.

function Cat (name, color){
this.name = name;
this.color = color;
}

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

this.speak = function(){
return 'kitty ' + this.name + 'is ' + this.color;
}

We can now create an instance of Cat like so:

var cat1 = new Cat('Ginger', 'orange');

cat1 is a new Cat object. The output for:

document.write(cat1.speak());

would be:
1

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

document.write(cat1 instanceof Cat);

Output:
2

https://blog.eduonix.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:

function colChange(cat) {
cat.name = 'Charly';
}

Now we’ll call the new function on cat1:

colChange(cat1);
document.write('Ginger has changed his name to ' + cat1.name);

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

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -