06.07.2017 Views

Mastering JavaScript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 5<br />

CarFactory.Sedan = function () {<br />

this.doors = 2;<br />

this.engine_capacity = 2;<br />

};<br />

CarFactory.SUV = function () {<br />

this.doors = 4;<br />

this.engine_capacity = 6;<br />

};<br />

var golf = CarFactory.make('Compact');<br />

var vento = CarFactory.make('Sedan');<br />

var touareg = CarFactory.make('SUV');<br />

golf.info(); //"This car has 4 doors and a 2 liter engine"<br />

We suggest that you try this example in JS Bin and understand the concept by<br />

actually writing its code.<br />

The mixin pattern<br />

Mixins help in significantly reducing functional repetition in our code and help<br />

in function reuse. We can move this shared functionality to a mixin and reduce<br />

duplication of shared behavior. You can then focus on building the actual<br />

functionality and not keep repeating the shared behavior. Let's consider the<br />

following example. We want to create a custom logger that can be used by any object<br />

instance. The logger will become a functionality shared across objects that want to<br />

use/extend the mixin:<br />

var _ = require('underscore');<br />

//Shared functionality encapsulated into a CustomLogger<br />

var logger = (function () {<br />

var CustomLogger = {<br />

log: function (message) {<br />

console.log(message);<br />

}<br />

};<br />

return CustomLogger;<br />

}());<br />

//An object that will need the custom logger to log system<br />

specific logs<br />

var Server = (function (Logger) {<br />

var CustomServer = function () {<br />

this.init = function () {<br />

this.log("Initializing Server...");<br />

};<br />

[ 133 ]<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!