nerdlyist
nerdlyist

Reputation: 2847

Use case for JavaScript Constructor Function

Finally decided to spend the time and get a grip on programming with JS rather than just stuffing spaghetti code into script tags at the end of a file. YDKJS is a great resource in my opinion. I have a pretty good understanding of factory patterns, IFFE and how objects and Object.create(...) are used.

One question that I cannot find an answer to is if constructor functions are still used and if so what would be the use case for them? The only reason I ask is because there are years of articles where that was the answer. Seems the idea was to get closer to class based inheritance (pre es6).

Essentially is it a design pattern I should invest time into learning?

Upvotes: 2

Views: 620

Answers (3)

Bergi
Bergi

Reputation: 664548

Are constructor functions still used?

Yes, of course they are. They are, and will continue to be, the dominant object construction pattern. They are as pervasive as object literals. They have the best performance optimisations in engines, and are used whenever large numbers of instances are needed. And the class pattern with a constructor for initialisation and a prototype for method inheritance is the most convenient pattern you get, with extra simple class syntax since ES6.

Upvotes: 1

lxg
lxg

Reputation: 13107

Of course constructors make sense and are used. Consider the following:

A = function()
{
    this.foo = "bar";
};

A.prototype.printFoo = function()
{
    console.log(this.foo);
};


B = function()
{
    this.foo = "foobar";
};

B.prototype = Object.create(A.prototype);

aInstance = new A();
aInstance.printFoo(); // foo

bInstance = new B();
bInstance.printFoo(); // foobar

A bit simplified: When calling a function with the new keyword, JS treats it as a constructor and passes an empty object named this into it. When assigning the constructor’s return value to a variable, it will contain the this object, extended by the properties of the function’s prototype as well as the modifications to this which were applied within the constructor. Therefore constructors are extremly useful and necessary in JS.

In ES6, constructors (and class-orientation in general) have become even more prominent; have a look at https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes for more.

Upvotes: 1

Meharaj M
Meharaj M

Reputation: 69

Constructor functions are designed to be used with new prefix. the new prefix creates a new object based on function's prototype and binds that object to the function's implicit this parameter.

Source: JavaScript the good parts by Douglas Crockford

Upvotes: 0

Related Questions