private/public fields, module, revealing module learning & development team telerik software...

35
JavaScript Patterns Private/Public fields, Module, Revealing Module Learning & Development Team http://academy.telerik.com Telerik Software Academy

Upload: andrew-chandler

Post on 30-Dec-2015

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

JavaScript PatternsPrivate/Public fields, Module, Revealing Module

Learning & Development Teamhttp://academy.telerik.com

Telerik Software Academy

Page 2: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

Table of Contents1. Public/Private fields in JavaScript

2. Module pattern

3. Revealing module pattern

4. Revealing prototype pattern

5. Singleton pattern

2

Page 3: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

Public/Private fieldsUsing the function scope

Page 4: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

Public/Private Fields Each variable is defined:

In the global scope (Public) In a function scope (Private)

4

var global = 5;

function myFunction() {var private = global;

function innerFunction(){var innerPrivate = private;

}}

Page 5: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

Public/Private fieldsLive Demo

Page 6: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

The Module PatternHide members

Page 7: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

Pros and Cons Pros:

“Modularize” code into re-useable objects

Variables/functions not in global namespace

Expose only public members

Cons: Not easy to extend

Some complain about debugging

7

Page 8: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

Module Pattern: Structure

8

var module = (function() {//private variables//private functions

return {//public memberssomeFunc: function() {…},anotherFunc: function() {…}

};}());

Structure:

Page 9: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

Module Pattern: Example

9

var controls = (function () { //hidden members function formatResult(name, value) { //… }

//visible members return { Calculator: function (name) { var result; result = 0; this.add = function (x) { //… }; this.subtract = function (x) { //…}; this.showResult = function () { //… }; } };}());var calc = new controls.Calculator('First');calc.add(7);calc.showResult();

Example:

Page 10: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

Module Pattern: Example

10

var controls = (function () { //hidden members function formatResult(name, value) { //… }

//visible members return { Calculator: function (name) { var result; result = 0; this.add = function (x) { //… }; this.subtract = function (x) { //…}; this.showResult = function () { //… }; } };}());var calc = new controls.Calculator('First');calc.add(7);calc.showResult();

Example:

The visible members create

closures with them

Page 11: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

var controls = (function () { //hidden members function formatResult(name, value) { //… }

//visible members return { Calculator: function (name) { var result; result = 0; this.add = function (x) { //… }; this.subtract = function (x) { //…}; this.showResult = function () { //… }; } };}());var calc = new controls.Calculator('First');calc.add(7);calc.showResult();

Module Pattern: Example

11

Example:

Visible function constructor

Page 12: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

Module Pattern: Summary

Module pattern provides encapsulation of variables and functions

Provides a way to add visibility (public versus private) to members

Each object instance creates new copies of functions in memory

12

Page 13: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

Module Pattern

Live Demo

Page 14: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

The Revealing Module PatternReveal the most interesting

members

Page 15: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

Revealing Module Pattern:

Pros and Cons Pros:

“Modularize” code into re-useable objects

Variables/functions taken out of global namespace

Expose only visible members "Cleaner" way to expose members Easy to change members privacy

Cons: Not easy to extend Some complain about debugging Hard to mock hidden objects for

testing

15

Page 16: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

16

var module = (function() {//hidden variables //hidden functions

return { //visible members

someFunc: referenceToFunctionanotherFunc: referenceToOtherFunction

};}());

Structure:

Revealing Module Pattern:

Structure

Page 17: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

17

var controls = (function () { //hidden function function formatResult(name, value) { // … }

var Calculator = (function () { var Calculator = function (name) { // … }; Calculator.prototype.add = function (x) { // … }; Calculator.prototype.subtract = function (x) { // … }; Calculator.prototype.showResult = function () { // …}; return Calculator; }());

return { Calculator: Calculator };}());

var calc = new controls.Calculator('First');

Example:

Revealing Module Pattern:

Example

Page 18: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

18

var controls = (function () { //hidden function function formatResult(name, value) { // … }

var Calculator = (function () { var Calculator = function (name) { // … }; Calculator.prototype.add = function (x) { // … }; Calculator.prototype.subtract = function (x) { // … }; Calculator.prototype.showResult = function () { // …}; return Calculator; }());

return { Calculator: Calculator };}());

var calc = new controls.Calculator('First');

Example:

Create the function constructor hidden

Revealing Module Pattern:

Example

Page 19: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

Revealing Module Pattern:

Example

19

var controls = (function () { //hidden function function formatResult(name, value) { // … }

var Calculator = (function () { var Calculator = function (name) { // … }; Calculator.prototype.add = function (x) { // … }; Calculator.prototype.subtract = function (x) { // … }; Calculator.prototype.showResult = function () { // …}; return Calculator; }());

return { Calculator: Calculator };}());

var calc = new controls.Calculator('First');

Example:

Expose (reveal) only references to hidden

member

Page 20: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

Module pattern provides encapsulation of variables and functions

Provides a way to add visibility (public versus private) to members

Extending objects can be difficult since no prototyping is used

20

Revealing Module Pattern:

Summary

Page 21: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

Revealing Module Pattern

Live Demo

Page 22: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

The Revealing Prototype PatternReveal the most interesting members

(again)

Page 23: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

Revealing Prototype Pattern:

Pros and Cons Pros: “Modularize” code into re-useable

objects Variables/functions taken out of

global namespace Expose only public members Functions are loaded into memory

once Extensible

Cons: "this" can be tricky Constructor is separated from

prototype

23

Page 24: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

Revealing Prototype Pattern:

Structure

24

var Constructor = function () {//constructor defined here

}

Constructor.prototype = (function() {//hidden variables //hidden functions

return { //exposed members

someFunc: pointerToSomeFuncanotherFunc: pointerToAnotherFunc

};}());

Structure:

Page 25: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

25

var Calculator = function (name) { // … };

Calculator.prototype = (function () { var add, subtract, showResult, formatResult;

add = function (x) { // … }; subtract = function (x) { // … }; showResult = function () { // … }; formatResult = function (name, value) { // … };

return { add: add, subtract: subtract, showResult: showResult };}());

var calc = new Calculator('First');

Example:

Revealing Prototype Pattern:Example

Page 26: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

Module pattern provides encapsulation of variables and functions

Provides a way to add visibility (exposed versus hidden) to members

Provides extension capabilities

26

Revealing Prototype Pattern:

Summary

Page 27: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

Revealing Prototype Pattern

Live Demo

Page 28: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

Singleton Pattern

One object to rule them all!

Page 29: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

Singleton Pattern: Structure

29

var module = function() { var instance, getInstance; return { getInstance: function(){ if(!instance){ instance = new Instance(); } return instance; } };}();

Structure:

Page 30: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

Singleton Pattern: Example

30

var controls = function () { var Calculator, calculatorInstance; Calculator = (function () { function Calculator() { //… } return Calculator; }()); return { getCalculator: function () { if (!calculatorInstance) { calculatorInstance = new Calculator(); } return calculatorInstance; } };}();var calculator = controls.getCalculator();

Example:

Page 31: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

Singleton Pattern

Live Demo

Page 32: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

Augmenting Modules

Live Demo

Page 33: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

форум програмиране, форум уеб дизайнкурсове и уроци по програмиране, уеб дизайн – безплатно

програмиране за деца – безплатни курсове и уроцибезплатен SEO курс - оптимизация за търсачки

уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop

уроци по програмиране и уеб дизайн за ученициASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC

безплатен курс "Разработка на софтуер в cloud среда"

BG Coder - онлайн състезателна система - online judge

курсове и уроци по програмиране, книги – безплатно от Наков

безплатен курс "Качествен програмен код"

алго академия – състезателно програмиране, състезания

ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NETкурсове и уроци по програмиране – Телерик академия

курс мобилни приложения с iPhone, Android, WP7, PhoneGap

free C# book, безплатна книга C#, книга Java, книга C#Дончо Минков - сайт за програмиранеНиколай Костов - блог за програмиранеC# курс, програмиране, безплатно

?

? ? ??

?? ?

?

?

?

??

?

?

? ?

Questions?

?

Arrays

http://csharpfundamentals.telerik.com

Page 34: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

Free Trainings @ Telerik Academy

“C# Programming @ Telerik Academy csharpfundamentals.telerik.com

Telerik Software Academy academy.telerik.com

Telerik Academy @ Facebook facebook.com/TelerikAcademy

Telerik Software Academy Forums forums.academy.telerik.com

Page 35: Private/Public fields, Module, Revealing Module Learning & Development Team  Telerik Software Academy

HomeworkCreate the Snake game using the Revealing module pattern. Design the game such that it has at least three modules.