Classes and Prototypes
In JavaScript, a class is a set of objects that inherit
properties from the same prototype object. The prototype object,
therefore, is the central feature of a class. In Example 6-1 we defined an inherit() function that returns a newly
created object that inherits from a specified prototype object. If we
define a prototype object, and then use inherit() to create objects that inherit
from it, we have defined a JavaScript class. Usually, the instances of
a class require further initialization, and it is common to define a
function that creates and initializes the new object. Example 9-1 demonstrates this: it defines a prototype object
for a class that represents a range of values and also defines a
“factory” function that creates and initializes a new instance of the
class.
Example 9-1. A simple JavaScript class
// range.js: A class representing a range of values.// This is a factory function that returns a new range object.functionrange(from,to){// Use the inherit() function to create an object that inherits from the// prototype object defined below. The prototype object is stored as// a property of this function, and defines the shared methods (behavior)// for all range objects.varr=inherit(range.methods);// Store the start and end points (state) of this new range object.// These are noninherited properties that are unique to this object.r.from=from;r.to=to;// Finally return the new objectreturnr;}// This prototype object defines ...
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