16.07.2017 Views

AngularJS Essentials

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

In order to promote encapsulation, we need to use a function instead of an object<br />

literal, as follows:<br />

var car = function () {<br />

var plate = "6MBV006";<br />

var color = "Blue";<br />

var entrance = "2013-12-09T23:46:15.186Z ";<br />

};<br />

Now, it's no longer possible to access any property of the object:<br />

> console.log(car.plate);<br />

undefined<br />

> console.log(car.color);<br />

undefined<br />

> console.log(car.entrance);<br />

undefined<br />

Chapter 4<br />

This happens because the function isolates its internal scope, and based on this<br />

principle, we are going to introduce the concept of the Revealing Module Pattern.<br />

This pattern, beyond taking care of the namespace, provides encapsulation. It allows<br />

the implementation of public and private methods, reducing the coupling within<br />

the components. It returns an object literal from the function, revealing only the<br />

desired properties:<br />

var car = function () {<br />

var plate = "6MBV006";<br />

var color = "Blue";<br />

var entrance = "2013-12-09T23:46:15.186Z ";<br />

return {<br />

plate: plate,<br />

color: color<br />

};<br />

};<br />

Also, we need to invoke the function immediately; otherwise, the variable car will<br />

receive the entire function. This is a very common pattern and is called IIFE, which is<br />

also known as Immediately-Invoked Function Expression:<br />

var car = function () {<br />

var plate = "6MBV006";<br />

var color = "Blue";<br />

var entrance = "2013-12-09T23:46:15.186Z ";<br />

[ 71 ]<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!