HTML and CSS Reference
In-Depth Information
return radius;
function diameter() {
return radius * 2;
function circumference() {
return diameter() * Math.PI;
// Expose privileged methods
this.radius = getSetRadius;
this.diameter = diameter;
this.circumference = circumference;
The new object no longer has a numeric radius property. Instead, it stores its
state in a local variable. This means that none of the nested functions needs this
anymore, so we can simplify the calls to them. Objects created with this constructor
will be robust, because outside code cannot tamper with its internal state except
through the public API.
7.4.3 Functional Inheritance
In his book, JavaScript: The Good Parts [5], and on his website, Douglas Crockford
promotes what he calls functional inheritance . Functional inheritance is the next
logical step from Listing 7.43, in which we've already eliminated most uses of the
this keyword. In functional inheritance, the use of this is eliminated completely
and the constructor is no longer needed. Instead, the constructor becomes a reg-
ular function that creates an object and returns it. The methods are defined as
nested functions, which can access the free variables containing the object's state.
Listing 7.44 shows an example.
Listing 7.44 Implementing circle using functional inheritance
function circle(radius) {
// Function definitions as before
return {
radius: getSetRadius,
Search WWH ::

Custom Search