HTML and CSS Reference
In-Depth Information
This approach has a serious drawback in that it creates three function objects
for every person object created. The original approach using a closure when adding
properties to the prototype will only ever create three function objects that are
shared between all circle objects. This means that creating n circle objects will cause
the latter version to use approximately n times as much memory as the original
suggestion. Additionally, object creation will be significantly slower because the
constructor has to create the function objects as well. On the other hand, property
resolution is quicker in the latter case because the properties are found directly on
the object and no access to the prototype chain is needed.
In deep inheritance structures, looking up methods through the prototype chain
can impact method call performance. However, in most cases inheritance structures
are shallow, in which case object creation and memory consumption should be
The latter approach also breaks our current inheritance implementation. When
the Sphere constructor invokes the Circle constructor, it copies over the circle
methods to the newly created sphere object, effectively shadowing the methods on
Sphere.prototype . This means that the Sphere constructor needs to change
as well if this is our preferred style.
7.4.2 Private Members and Privileged Methods
In the same way private functions may be created inside the constructor, we can
create private members here, allowing us to protect the state of our objects. In
order to make anything useful with this we'll need some public methods that can
access the private properties. Methods created in the same scope—meaning the
constructor—will have access to the private members, and are usually referred to
as “privileged methods.” Continuing our example, Listing 7.43 makes radius a
private member of Circle objects.
Listing 7.43 Using private members and privileged methods
function Circle(radius) {
function getSetRadius() {
if (arguments.length > 0) {
if (arguments[0] < 0) {
throw new TypeError("Radius should be >= 0");
radius = arguments[0];
Search WWH ::

Custom Search