11.09.2015 Views

Typescript Deep Dive by Basarat Ali Syed

Typescript Deep Dive by Basarat Ali Syed

Typescript Deep Dive by Basarat Ali Syed

SHOW MORE
SHOW LESS

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

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

TypeScript <strong>Deep</strong> <strong>Dive</strong><br />

Namespaces<br />

Namespaces provide you with a convenient syntax around a common pattern used in JavaScript:<br />

(function(something) {<br />

something.foo = 123;<br />

})(something || something = {})<br />

Basically something || something = {} allows an anonymous function function(something){} to add stuff to an existing<br />

object (the something || portion) or start a new object then add stuff to that object (the || something = {} portion). This<br />

means that you can have two such blocks split <strong>by</strong> some execution boundary :<br />

(function(something) {<br />

something.foo = 123;<br />

})(something || something = {})<br />

console.log(something); // {foo:123}<br />

(function(something) {<br />

something.bar = 456;<br />

})(something || something = {})<br />

console.log(something); // {foo:123, bar:456}<br />

This is commonly used in the JavaScript land for making sure that stuff doesn't leak into the global namespace. With file<br />

based modules you don't need to worry about this, but the pattern is still useful for logical grouping of a bunch of functions.<br />

Therefore TypeScript provides the namespace keyword to group these e.g.<br />

namespace utility {<br />

export function log(msg) {<br />

console.log(msg);<br />

}<br />

export function error(msg) {<br />

console.error(msg);<br />

}<br />

}<br />

// usage<br />

utility.log('Call me');<br />

utility.error('maybe!');<br />

The namespace keyword generates the same JavaScript that we saw earlier:<br />

(function (utility) {<br />

// Add stuff to utility<br />

})(utility || (utility = {}));<br />

One thing to note is that namespaces can be nested so you can do stuff like namespace utility.messaging to nest a<br />

messaging namespace under utility .<br />

Namespaces<br />

47

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

Saved successfully!

Ooh no, something went wrong!