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:
functionGreeting(item){this.log=function(){console.log('Hello '+item+'!');};}varhello=newGreeting('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:
newGreeting('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:
functionGreeting(item){this.item=
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access