Chapter 2. Constructors and Prototypes

Constructors are a way of creating objects, and can be initiated via the new keyword. Many instances of an object can be created. Prototypes are one of the more powerful features of JavaScript, and allow the developer to declare a method or property that all instances of an object will inherit.

This chapter is less about building on your existing jQuery knowledge than teaching you a method you can use to enhance your jQuery code. To an extent, it will also help you understand how jQuery works, as jQuery itself uses prototypes.

Constructors

Constructors are functions that are called by the new keyword. For example:

function Greeting(item) {
        this.log = function () {
                console.log('Hello ' + item + '!');
        };
}

var hello = new Greeting('world');
hello.log(); // Hello world!

Tip

Begin the names of your constructors with a capital letter; this will help you remember whether it is a function or a constructor. This is fairly common practice, so you should be able to recognize constructors in other people’s code, too.

It is possible to create the object and call a method on the same line, which can often be useful:

new Greeting('alien').log(); // Hello alien!

In other languages, the closest thing to constructors are classes. Classes have constructor functions, which in that context are functions that are run when a class is used to create an object. It’s easier to specify code that should be run on creation in JavaScript:

function Greeting(item) {
        this.item = 

Get Learning from jQuery now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.