HTML and CSS Reference
In-Depth Information
Listing 7.46 Implementing sphere using functional inheritance
function sphere(radius) {
var sphereObj = circle(radius);
var circleArea = sphereObj.area;
function area() {
return 4 * circleArea.call(this);
}
sphereObj.area = area;
return sphereObj;
}
The inheriting function may of course provide private variables and functions
of its own. It cannot, however, access the private variables and functions of the
object it builds upon.
The functional style is an interesting alternative to the pseudo-classical con-
structors, but comes with its own limitations. The two most obvious drawbacks
of this style of coding are that every object keeps its own copy of every function,
increasing memory usage, and that in practice we aren't using the prototype chain,
which means more cruft when we want to call the “super” function or something
similar.
7.5 Object Composition and Mixins
In classical languages, class inheritance is the primary mechanism for sharing behav-
ior and reusing code. It also serves the purpose of defining types, which is important
in strongly typed languages. JavaScript is not strongly typed, and such classification is
not really interesting. Even though we have the previously discussed construc-
tor property and the instanceof operator, we're far more often concerned
with what a given object can do. If it knows how to do the things we are interested
in, we are happy. Which constructor created the object to begin with is of less
interest.
JavaScript's dynamic object type allows for many alternatives to type inheritance
in order to solve the case of shared behavior and code reuse. In this section we'll
discuss how we can make new objects from old ones and how we can use mixins to
share behavior.
 
 
Search WWH ::




Custom Search