What is the constructor?


#1

I'm confused. What is the constructor? Please reply to me as soon as possible.


#2

Uh I went through this topic yesterday.
I think it is a function which builds a object from the given set of instructions.

Well that is what I know of


#3

@betarunner19143 the constructor of a class(function) tells you how to make an object of that class.

Check out this code snippet

See if you can understand what is going on


#4

A constructor function is an object model from which we may fashion like instances that share the same properties but with their own unique values. It is referred to as a Class. We may extend the prototype of a class to make available a range of functions called methods that every instance can call on its own context.

@rydan gives a good example. In this example the methods are included as direct properties in the constructor. We learn a more efficient way of doing this when we cover prototype. Consider,

function Person(name, age) {
    this.name = name;
    this.age = age;
}

Now when we create some instances, they will all have a name and an age property with their own values.

bill = new Person("Bill", 19);
mary = new Person("Mary", 20);

As it stands, these instances inherit from Person, but they also inherit from the Object.prototype so have all the built in object methods at their disposal.

We can dynamically extend the Person.prototype to include some useful methods:

Person.prototype.setAge = function (newAge) {
    this.age = newAge;
};
Person.prototype.attributes = function () {
    return "Name: " + this.name + ", Age: " + this.age;
};

and we can call them on each instance:

bill.setAge(21);
console.log(bill.attributes()); // Name: Bill, Age: 21
mary.setAge(19);
console.log(mary.attributes()); // Name: Mary, Age: 19

#5

Yes Using an object prototype to extend it is more efficient.Thanks for the pointer @mtf