CHAPTER 20 Ensuring Correct Use of Mixins

WHAT’S IN THIS CHAPTER?            

  • Identifying situations in which using a mixin is appropriate
  • Creating an extend function that safely “mixes” one object into another
  • Creating and testing a mixin for use with an extend function
  • Creating and testing a functional mixin

WROX.COM CODE DOWNLOADS FOR THIS CHAPTER

You can find the wrox.com code downloads for this chapter at www.wrox.com/go/reliablejavascript on the Download Code tab. The files are in the Chapter 20 download and individually named according to the filenames noted throughout this chapter.

Mixins are a mechanism for code reuse in which the properties of one object, the mixin, are utilized by another, the target. This sounds similar to the topic covered in Chapter 19, method-borrowing, and it is. Both techniques may be used to share method implementations from one object to another, but there are a few key differences:

  • The mixin object provides both data and methods to the target, whereas method-borrowing, as the name implies, limits the sharing to methods.
  • The mixin object exists only to provide its properties to a target; it is not intended to function on its own.
  • The mixin object’s properties are added directly to the target object; the target object doesn’t retain an explicit reference to the mixin.

Mixins are ideally suited for implementing functionality common to many object types, but not dependent upon the details of any of those types.

Suppose you’d like all of ...

Get Reliable JavaScript: How to Code Safely in the World's Most Dangerous Language now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.