Constructor patterns

The Constructor pattern uses a singular constructor and then manually fills its prototype with methods and properties. This was the traditional approach for creating classical OOP-like classes in JavaScript before the class definition syntax existed.

Typically, it begins with the definition of a constructor as a function declaration:

function Book(title) {
// Initialization Logic
this.title = title;
}

This would then be followed by assigning individual methods to the prototype:

Book.prototype.getNumberOfPages = function() { /* ... */ };
Book.prototype.renderFrontCover: function() { /* ... */ };
Book.prototype.renderBackCover: function () { /* ... */ };

Or it would be followed by replacing the entire prototype with an object literal:

Book.prototype = {
getNumberOfPages: function() { /* ... */ },
renderFrontCover: function() { /* ... */ },
renderBackCover: function () { /* ... */ }
};

The latter approach tends to be preferred as it's more encapsulated and succinct. Nowadays, of course, if you wished to use the Constructor pattern, you would likely opt for method definitions as they take up less space than individual key-value pairs:

Book.prototype = {
getNumberOfPages() { /* ... */ },
renderFrontCover() { /* ... */ },
renderBackCover () { /* ... */ }
};

The instantiation of a constructor would be via the new keyword:

const myBook = new Book();

This creates a new object that has an internal [[Prototype]] of the constructor's prototype (that is, our object, which contains getNumberOfPages, renderFrontCover, and renderBackCover).

If you're struggling to recall the prototypal mechanisms that underlie constructors and instantiation, then please revisit Chapter 6, Primitives and Built-in Types, and, specifically, the section called The prototype.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.172.93