Skip to Content
JavaScript: The Definitive Guide, Fourth Edition
book

JavaScript: The Definitive Guide, Fourth Edition

by David Flanagan
November 2001
Intermediate to advanced
936 pages
68h 43m
English
O'Reilly Media, Inc.
Content preview from JavaScript: The Definitive Guide, Fourth Edition

Prototypes and Inheritance

We’ve seen how inefficient it can be to use a constructor to assign methods to the objects it initializes. When we do this, each and every object created by the constructor has identical copies of the same method properties. There is a much more efficient way to specify methods, constants, and other properties that are shared by all objects in a class.

JavaScript objects “inherit” properties from a prototype object.[27] Every object has a prototype; all of the properties of the prototype object appear to be properties of any objects for which it is a prototype. That is, each object inherits properties from its prototype.

The prototype of an object is defined by the constructor function that was used to create and initialize the object. All functions in JavaScript have a prototype property that refers to an object. This prototype object is initially empty, but any properties you define in it will be inherited by all objects created by the constructor.

A constructor defines a class of objects and initializes properties, such as width and height, that are the state variables for the class. The prototype object is associated with the constructor, so each member of the class inherits exactly the same set of properties from the prototype. This means that the prototype object is an ideal place for methods and other constant properties.

Note that inheritance occurs automatically, as part of the process of looking up a property value. Properties are

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.
Start your free trial

You might also like

JavaScript: A Beginner's Guide, Fourth Edition, 4th Edition

JavaScript: A Beginner's Guide, Fourth Edition, 4th Edition

John Pollock
JavaScript Cookbook, 3rd Edition

JavaScript Cookbook, 3rd Edition

Adam D. Scott, Matthew MacDonald, Shelley Powers

Publisher Resources

ISBN: 0596000480Supplemental ContentCatalog PageErrata