SlideShare uma empresa Scribd logo
1 de 17
Baixar para ler offline
love.apply(i,[you]);
undefined
Say	it	with	JavaScript!		
Topics:
Objects & C.
Functions & C.
Closure
Inheritance
Namespaces & Temp Scope
Module Pattern
Dispatching
Putting it all together
Unit Testing
Objects & C.
//Creating objects
var myObj1 = {};
var myObj2 = new Object();
//Creating arrays
var myArr1 = [];
var myArr2 = new Array();
var myArr3 = [1, "a"];
myArr3.length == 2 //true
//Exploiting objects
typeof myObj1 //"object"
myObj1 instanceof Object //true
myObj1.constructor //function Object() { [native
code] }
//Exploiting arrays
typeof myArr1 //"object"
myArr1 instanceof Array //true (within same frame)
myArr1 instanceof Object //true
myArr1.constructor //function Array() { [native code]
}
//Adding properties
myObj1.x = 5;
myObj2["x"] = 5;
myObj2.double = function(x) { return x*2; }
myObj1["x"] == myObj2.x //true
myObj2.x //5
myArr1.x = "test";
myArr1["y"] = "test";
myArr1.y == myArr1["x"] //true
//Test
var testArr = [];
testArr["x"] = "element x";
testArr["y"] = "element 0";
testArr.length //???
//Literals
var person = {
name: "giovanni",
age: 41,
rejuvenate: function() {
this.age--;
}
}
//The proto chain
var developer = {
salary: 999999
}
//Using Object.create
var developer = Object.create(person);
developer.salary = 999999;
developer.name //"giovanni"
developer.__proto__ == person; //true
//Test
person.age = 10;
developer.age //???
Functions	&	C.	
//Defining functions
function sayHello1() {
console.log("Hi there!");
}
var sayHello2 = function() {
console.log("Hi there!");
}
//Test
sayHello1.name //??
sayHello2.name //??
typeof sayHello1 //function
sayHello1 instanceof Object //true
sayHello1.constructor //function Function() {…}
var fn = new Function("","console.log('Hi there!')");
//Calling function
var sayHelloTo = function sayHelloTo(name) {
return this.greeting + " " + name;
}
sayHelloTo("Giovanni"); //"undefined Giovanni"
window.greeting = "Good morning"
sayHelloTo("Giovanni"); //"Good morning Giovanni"
//Calling functions within a context
var evening = { greeting: "Good evening"};
//"Good evening Giovanni"
sayHelloTo.apply(evening, ["Giovanni"]);
sayHelloTo.call(evening, "Giovanni");
var urbanGreeter = {
greeting: "Sup",
greet: sayHelloTo
}
urbanGreeter.greet("Giovanni") //"Sup Giovanni"
//Test
//What is this function doing?
function bind(fnContext, fn) {
return function() {
return fn.apply(fnContext, arguments);
}
}
//Test
function reverseName() {
return this.name.split("").reverse().join("");
}
var r = bind({name: "giovanni"}, reverseName);
r(); //??
Closures	
//Defining closures
function counter(startAt){
var count = startAt;
return function(){
console.log(++count)
};
}
var next = counter(0);
next(); //1
next(); //2
next(); //3
//Closures with input parameters
var quo = function (status) {
return {
get_status: function ( ) {
return status;
}
};
};
var myQuo = quo("active");
myQuo.get_status(); //"active"
//Test
var handlers = [];
for (var i = 0; i < 10; i += 1) {
handlers.push(
function() { return i; }
);
};
handlers[2](); //???
handlers[6](); //???
//Test
var handlers = [];
for (var i = 0; i < 10; i += 1) {
handlers.push(
function(i) {
return function() { return i;};
}(i)
);
};
var index = handlers.length;
while(index) console.log(handlers[--index]()); //???
//Using closures for encapsulation
function buildProduct() {
var productID = 999;
return {
getID: function () {
return productID;
},
setID: function (theNewID) {
productID = theNewID;
}
}
}
var product = buildProduct();
product.getID(); // 999
product.setID(478);
product.getID(); // 478

//Test
var shortCut = product.getID;
shortCut(); //???
Inheritance
//Inheritance with the ‘new’ operator
//constructor
function Person(name, age){
this.name = name;
this.age = age;
}
Person.prototype.getName = function(){
return this.name;
};
Person.prototype.getAge = function(){
return this.age;
};
Person.prototype.title = "Mr.";
var badPerson = Person("Max",30);
badPerson == undefined; //true
window.name == "Max"; //true
var goodPerson1 = new Person("Giovanni",41);
var goodPerson2 = new Person("John",30);
goodPerson1.getName() == "Giovanni"; //true
goodPerson2.getAge() == "30"; //true
goodPerson2.title = "Mr."; //true
//Test
goodPerson2.age = 31;
goodPerson2.title = "Dr.";
console.log(goodPerson1.age); //??
console.log(goodPerson1.title); //??
//inheritance chains
function Worker(name, age, profession, salary) {
Person.call(this,name,age);
this.profession = profession;
this.salary = salary;
}
Worker.prototype = new Person();
//Added for legacy code compatibility
Worker.prototype.constructor = Worker;
Worker.prototype.fire = function() {
this.profession = "unemployed";
}
Worker.prototype.giveBigRaise = function() {
this.salary += 10000;
}
var w1 = new Worker("Giovanni", 41, "developer", 0);
var w2 = new Worker("John", 43, "developer", 0);
//Test
w1.giveBigRaise();
w1.salary; //??
w2.salary; //??
w1.getAge(); //??
w1.title == "Mr."; //??
w1 instance of Worker; //??
W2 instance of Worker; //??
w1 instance of Person; //??
w1 instance of Object; //??
//Extending native types – forEach polyfill
if (!Array.prototype.forEach) {
Array.prototype.forEach = function (fn, scope) {
for (var i = 0, l = this.length; i < l; ++i) {
if (i in this) {
fn.call(scope, this[i], i, this);
}
}
};
}
['a','b','c'].forEach(
function(elm, index, ctx) {
console.log(index +'. ' + elm);
},
window
);
//Inheritance with Object.create
var myMammal = {
name : 'Herb the Mammal',
get_name : function ( ) {
return this.name;
},
says : function ( ) {
return this.saying || '';
}
};
var myCat1 = createCat('Henrietta');
var myCat2 = createCat('Rocky');
function createCat(name) {
var obj = Object.create(myMammal);
obj.name = name;
obj.saying = 'meow';
obj.purr = function (n) {
return 'r-r-r-r-r';
};
obj.get_name = function ( ) {
return this.says( ) + ' ' + this.name + ' ';
};
return obj;
}
myCat2.get_name(); //??
myMammal.bloodTemperature = 'warm’;
myCat1.bloodTemperature; //??
//Functional Inheritance
function base(spec) {
var that = {};
that.name = spec.name;
return that; // Return the object
}
function child(spec) {
var that = base(spec);
that.sayHello = function() {
return 'Hello, I'm ' + that.name;
};
return that; // Return it
}
// Usage
var object = child({ name: 'a functional object' });
console.log(object.sayHello());
//Mixins
var asButton = function() {
this.hover = function() {
console.log('hover handler');
};
this.press = function() {
console.log('press handler');
};
this.fire = function() {
return this.action();
};
return this;
};
var asCircle = function() {
this.area = function() {
return Math.PI * this.radius * this.radius;
};
this.grow = function() {
this.radius++;
};
this.shrink = function() {
this.radius--;
};
return this;
};
var RoundButton = function(radius, label, action) {
this.radius = radius;
this.label = label;
this.action = action;
};
asButton.call(RoundButton.prototype);
asCircle.call(RoundButton.prototype);
var button1 = new RoundButton(4, 'yes!',
function() {return 'you said yes!';}
);
button1.fire(); //'you said yes!'
Namespaces	&	Temp.	Scope
//Creating namespaces manually
var afsi = afsi || {};
afsi.utilities = myApp.utilities || {};
afsi.utilities.sayHello = function(name) {
return "Hi " + name;
}
//A namespace utility
var afsi = afsi || {};
afsi.namespace = function namespace(namespaceString) {
var parts = namespaceString.split('.'),
parent = window,
currentPart = '';
for(var i = 0, length = parts.length; i < length; i++) {
currentPart = parts[i];
parent[currentPart] = parent[currentPart] || {};
parent = parent[currentPart];
}
}
//Defining and using a namespace
afsi.namespace("afsi.utilities");
var afsi.utilities.sayHello = function(name) {
return "Hi " + name;
}
//‘Wrapping’ techniques
(function(){
var myLib = window.myLib = function(){
// Initialize
};
// ...
})();
---------------------------------------------
var myLib = (function(){
function myLib(){
// Initialize
}
// ...
return myLib;
})();
---------------------------------------------
(function( window, document, NS, undefined ){
NS.variableName = "string value";
NS.methodName = function() {};
// ...
}(window,
window.document,
(window.NS = window.NS || {})
)
);
---------------------------------------------
function MyScript(){}
(function() {
var THIS = this;
function defined(x) {
alert(THIS); //points to MyScript()
}
// ...
}).apply(MyScript);
Module	Pattern	–	(singleton,	revealing)
var afsi = afsi || {};
var afsi.calculator = (function () {
var _m = 0;
function _add(n1,n2) {
return n1+n2;
}
function _substract(n1,n2) {
return n1-n2;
}
function _setM(m) {
return _m = m;
}
function _getM() {
return _m;
}
return {
add: _add,
substract: _substract,
setM: _setM,
getM: _getM
};
}());
Module	Pattern	–	constructor	(OOP)
var afsi = afsi || {};
afsi.MyClass = (function(){
var _privateStaticVar = "I am a static private variable";
var _privateFunction = function() {
return "I am a private function";
};
var Constructor = function(options) {
this.instanceVar = "I am an public instance variable";
this.setPrivateStaticVar = function(x) {
_privateStaticVar = x;
};
this.getPrivateStaticVar = function() {
return _privateStaticVar;
};
this.exposePrivateFunction = _privateFunction;
};
Constructor.prototype = {
constructor: afsi.MyClass,
name: "afsi.MyClass",
version: "1.0"
};
return Constructor;
}());
var v1 = new afsi.MyClass(options);
var v2 = new afsi.MyClass(options);
Module	Pattern	–	factory	(functional,	revealing)
var afsi = afsi || {};
afsi.calculator = (function(){
var _add = function (n1, n2) {
return n1+n2;
};
var _substract = function (n1, n2) {
return n1-n2;
};
var _calculatorFactory = function () {
var _m = 0;
var _setM = function (m) {
_m = m;
};
var _getM = function () {
return _m;
};
return {
add: _add,
substract: _substract,
setM: _setM,
getM: _getM
};
};
return _calculatorFactory;
}());
var calc = afsi.calculator();
Dispatching	(Publisher/Subscriber)
var afsi = afsi || {};
afsi.messenger = (function () {
var _messengerFactory = function() {
var _messages = [];
var _subscribeMessage = function (messageName, callBack) {
if (typeof messageName === "string" && typeof callBack === "function") {
if (typeof _messages[messageName] === "undefined") {
_messages[messageName] = [];
}
_messages[messageName].push(callBack);
}
};
var _sendMessage = function (messageName, message) {
if (typeof messageName === "string" && typeof _messages[messageName] !== "undefined") {
for (var _counter = 0, max = _messages[messageName].length; _counter < max; _counter++) {
_messages[messageName][_counter](message);
}
}
};
return {
subscribeMessage: _subscribeMessage,
sendMessage: _sendMessage
};
}
return _messengerFactory;
} ());
Putting	it	all	together
//Controller
afsi.namespace("afsi.myPage.controller");
afsi.myPage.controller = (function () {
var _processSearchData (searchData) {
//process the search data
return searchData;
}
var _ctrFactory = function (model,view, messenger) {
messenger.subscribeMessage(
"myPage.search_onkeypress",
function (text) {
model.searchProducts(text);
}
);
messenger.subscribeMessage(
"myPage.search_result",
function (searchData) {
searchData = _processSearchData(searchData);
view.showSearchResult(searchData);
}
);
};
return _ctrFactory;
} ());
//View
afsi.namespace("afsi.myPage.view");
afsi.myPage.view = (function () {
var _showSearchResult = function(searchData){
//bind UI with searchData
…
}
var _viewFactory = function (messenger) {
$("#searchInput").on("keypress", {},
function (event) {
messenger.sendMessage(
"myPage.search_onkeypress",
this.value
);
}
);
return {
showSearchResult: _showSearchResult
};
}
return _viewFactory
} ());
//Model
afsi.namespace("afsi.myPage.model");
afsi.myPage.model = (function () {
var _modelFactory = function (messenger) {
var _searchProducts = function(text){
$.ajax({
url: "/api/Products/SearchProducts?q="+text,
type: 'GET',
cache: false,
success: function (result) {
messenger.sendMessage(
"myPage.search_result",
Result
);
},
error: function (result) {
alert("Some error message")
}
});
}
return {
searchProducts: _searchProducts
};
}
return _modelFactory;
} ());
//Page initialization
$(function () {
var messenger = afsi.messenger();
afsi.myPage.controller(
afsi.myPage.model(messenger),
afsi.myPage.view(messenger),
messenger
);
});
Unit	Testing	(QUnit)
(function() {
module('Dispatcher Test');
test( "Subscriber should be called and receceive the message", function() {
//expected assertion #
expect(3);
//reate instance
var m = afsi.messenger();
//set up
m.subscribeMessage("afsi.test", function(message) {
//assertions
ok( true, "function called" );
ok( typeof message !== 'undefined', "message is defined" );
ok( message.data === 'something', "data has the correct value" );
});
//stimulus
m.sendMessage("afsi.test", { data: 'something' })
});
…
}());
confirm("Questions?")
References
Eloquent JavaScript
http://eloquentjavascript.net/index.html
Learning Advanced Javascript
http://ejohn.org/apps/learn/
Google Talks: How JavaScript Works
http://www.youtube.com/watch?v=ljNi8nS5TtQ
Prototypes and Inheritance in JavaScript
http://msdn.microsoft.com/en-us/magazine/ff852808.aspx
Functional inheritance vs. prototypal inheritance
http://www.richard-foy.fr/blog/2011/10/30/functional-inheritance-vs-prototypal-inheritance/
Namespacing in JavaScript
http://javascriptweblog.wordpress.com/2010/12/07/namespacing-in-javascript/
JavaScript Module Pattern: In-Depth
http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html
ECMAScript 5 Strict Mode, JSON, and More
http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/#!
QUnit: Introduction to Unit Testing
http://qunitjs.com/intro/
alert("Thank You!");

Mais conteúdo relacionado

Mais procurados

ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation JavascriptRamesh Nair
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016Manoj Kumar
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!Brendan Eich
 
How to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftHow to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftGiordano Scalzo
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesDragos Ionita
 
JavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineJavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineRaimonds Simanovskis
 
Testing your javascript code with jasmine
Testing your javascript code with jasmineTesting your javascript code with jasmine
Testing your javascript code with jasmineRubyc Slides
 
Writing Your App Swiftly
Writing Your App SwiftlyWriting Your App Swiftly
Writing Your App SwiftlySommer Panage
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs偉格 高
 
Javascript essential-pattern
Javascript essential-patternJavascript essential-pattern
Javascript essential-pattern偉格 高
 
Building fast interpreters in Rust
Building fast interpreters in RustBuilding fast interpreters in Rust
Building fast interpreters in RustIngvar Stepanyan
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Tsuyoshi Yamamoto
 
Pyimproved again
Pyimproved againPyimproved again
Pyimproved againrik0
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
Minimizing Decision Fatigue to Improve Team Productivity
Minimizing Decision Fatigue to Improve Team ProductivityMinimizing Decision Fatigue to Improve Team Productivity
Minimizing Decision Fatigue to Improve Team ProductivityDerek Lee Boire
 

Mais procurados (20)

ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
 
How to Clone Flappy Bird in Swift
How to Clone Flappy Bird in SwiftHow to Clone Flappy Bird in Swift
How to Clone Flappy Bird in Swift
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
 
JavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineJavaScript Unit Testing with Jasmine
JavaScript Unit Testing with Jasmine
 
Testing your javascript code with jasmine
Testing your javascript code with jasmineTesting your javascript code with jasmine
Testing your javascript code with jasmine
 
this
thisthis
this
 
Writing Your App Swiftly
Writing Your App SwiftlyWriting Your App Swiftly
Writing Your App Swiftly
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
 
Javascript essential-pattern
Javascript essential-patternJavascript essential-pattern
Javascript essential-pattern
 
Building fast interpreters in Rust
Building fast interpreters in RustBuilding fast interpreters in Rust
Building fast interpreters in Rust
 
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
Grails 1.2 探検隊 -新たな聖杯をもとめて・・・-
 
Pyimproved again
Pyimproved againPyimproved again
Pyimproved again
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
ES2015 workflows
ES2015 workflowsES2015 workflows
ES2015 workflows
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
Minimizing Decision Fatigue to Improve Team Productivity
Minimizing Decision Fatigue to Improve Team ProductivityMinimizing Decision Fatigue to Improve Team Productivity
Minimizing Decision Fatigue to Improve Team Productivity
 

Semelhante a Say It With Javascript

Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScriptkvangork
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascriptkvangork
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developersStoyan Stefanov
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesAnkit Rastogi
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Seri Moth
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascriptMiao Siyu
 
Get started with YUI
Get started with YUIGet started with YUI
Get started with YUIAdam Lu
 
JavaScript Classes and Inheritance
JavaScript Classes and InheritanceJavaScript Classes and Inheritance
JavaScript Classes and Inheritancemarcheiligers
 
05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboardsDenis Ristic
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: FunctionsAdam Crabtree
 
Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015Lukas Ruebbelke
 
Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oopLearningTech
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
JSDay Italy - Backbone.js
JSDay Italy - Backbone.jsJSDay Italy - Backbone.js
JSDay Italy - Backbone.jsPierre Spring
 

Semelhante a Say It With Javascript (20)

Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScript
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascript
 
Javascript tid-bits
Javascript tid-bitsJavascript tid-bits
Javascript tid-bits
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
Js hacks
Js hacksJs hacks
Js hacks
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
Get started with YUI
Get started with YUIGet started with YUI
Get started with YUI
 
Javascript - Beyond-jQuery
Javascript - Beyond-jQueryJavascript - Beyond-jQuery
Javascript - Beyond-jQuery
 
JavaScript Classes and Inheritance
JavaScript Classes and InheritanceJavaScript Classes and Inheritance
JavaScript Classes and Inheritance
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
 
05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
 
Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015
 
Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oop
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
JSDay Italy - Backbone.js
JSDay Italy - Backbone.jsJSDay Italy - Backbone.js
JSDay Italy - Backbone.js
 

Mais de Giovanni Scerra ☃

Mais de Giovanni Scerra ☃ (6)

Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Getting Started With QA Automation
Getting Started With QA AutomationGetting Started With QA Automation
Getting Started With QA Automation
 
Thoughtful Software Design
Thoughtful Software DesignThoughtful Software Design
Thoughtful Software Design
 
Improving Estimates
Improving EstimatesImproving Estimates
Improving Estimates
 
Getting Started With Testing
Getting Started With TestingGetting Started With Testing
Getting Started With Testing
 
Unit Testing SQL Server
Unit Testing SQL ServerUnit Testing SQL Server
Unit Testing SQL Server
 

Último

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 

Último (20)

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 

Say It With Javascript

  • 1. love.apply(i,[you]); undefined Say it with JavaScript! Topics: Objects & C. Functions & C. Closure Inheritance Namespaces & Temp Scope Module Pattern Dispatching Putting it all together Unit Testing
  • 2. Objects & C. //Creating objects var myObj1 = {}; var myObj2 = new Object(); //Creating arrays var myArr1 = []; var myArr2 = new Array(); var myArr3 = [1, "a"]; myArr3.length == 2 //true //Exploiting objects typeof myObj1 //"object" myObj1 instanceof Object //true myObj1.constructor //function Object() { [native code] } //Exploiting arrays typeof myArr1 //"object" myArr1 instanceof Array //true (within same frame) myArr1 instanceof Object //true myArr1.constructor //function Array() { [native code] } //Adding properties myObj1.x = 5; myObj2["x"] = 5; myObj2.double = function(x) { return x*2; } myObj1["x"] == myObj2.x //true myObj2.x //5 myArr1.x = "test"; myArr1["y"] = "test"; myArr1.y == myArr1["x"] //true //Test var testArr = []; testArr["x"] = "element x"; testArr["y"] = "element 0"; testArr.length //??? //Literals var person = { name: "giovanni", age: 41, rejuvenate: function() { this.age--; } } //The proto chain var developer = { salary: 999999 } //Using Object.create var developer = Object.create(person); developer.salary = 999999; developer.name //"giovanni" developer.__proto__ == person; //true //Test person.age = 10; developer.age //???
  • 3. Functions & C. //Defining functions function sayHello1() { console.log("Hi there!"); } var sayHello2 = function() { console.log("Hi there!"); } //Test sayHello1.name //?? sayHello2.name //?? typeof sayHello1 //function sayHello1 instanceof Object //true sayHello1.constructor //function Function() {…} var fn = new Function("","console.log('Hi there!')"); //Calling function var sayHelloTo = function sayHelloTo(name) { return this.greeting + " " + name; } sayHelloTo("Giovanni"); //"undefined Giovanni" window.greeting = "Good morning" sayHelloTo("Giovanni"); //"Good morning Giovanni" //Calling functions within a context var evening = { greeting: "Good evening"}; //"Good evening Giovanni" sayHelloTo.apply(evening, ["Giovanni"]); sayHelloTo.call(evening, "Giovanni"); var urbanGreeter = { greeting: "Sup", greet: sayHelloTo } urbanGreeter.greet("Giovanni") //"Sup Giovanni" //Test //What is this function doing? function bind(fnContext, fn) { return function() { return fn.apply(fnContext, arguments); } } //Test function reverseName() { return this.name.split("").reverse().join(""); } var r = bind({name: "giovanni"}, reverseName); r(); //??
  • 4. Closures //Defining closures function counter(startAt){ var count = startAt; return function(){ console.log(++count) }; } var next = counter(0); next(); //1 next(); //2 next(); //3 //Closures with input parameters var quo = function (status) { return { get_status: function ( ) { return status; } }; }; var myQuo = quo("active"); myQuo.get_status(); //"active" //Test var handlers = []; for (var i = 0; i < 10; i += 1) { handlers.push( function() { return i; } ); }; handlers[2](); //??? handlers[6](); //??? //Test var handlers = []; for (var i = 0; i < 10; i += 1) { handlers.push( function(i) { return function() { return i;}; }(i) ); }; var index = handlers.length; while(index) console.log(handlers[--index]()); //??? //Using closures for encapsulation function buildProduct() { var productID = 999; return { getID: function () { return productID; }, setID: function (theNewID) { productID = theNewID; } } } var product = buildProduct(); product.getID(); // 999 product.setID(478); product.getID(); // 478
 //Test var shortCut = product.getID; shortCut(); //???
  • 5. Inheritance //Inheritance with the ‘new’ operator //constructor function Person(name, age){ this.name = name; this.age = age; } Person.prototype.getName = function(){ return this.name; }; Person.prototype.getAge = function(){ return this.age; }; Person.prototype.title = "Mr."; var badPerson = Person("Max",30); badPerson == undefined; //true window.name == "Max"; //true var goodPerson1 = new Person("Giovanni",41); var goodPerson2 = new Person("John",30); goodPerson1.getName() == "Giovanni"; //true goodPerson2.getAge() == "30"; //true goodPerson2.title = "Mr."; //true //Test goodPerson2.age = 31; goodPerson2.title = "Dr."; console.log(goodPerson1.age); //?? console.log(goodPerson1.title); //?? //inheritance chains function Worker(name, age, profession, salary) { Person.call(this,name,age); this.profession = profession; this.salary = salary; } Worker.prototype = new Person(); //Added for legacy code compatibility Worker.prototype.constructor = Worker; Worker.prototype.fire = function() { this.profession = "unemployed"; } Worker.prototype.giveBigRaise = function() { this.salary += 10000; } var w1 = new Worker("Giovanni", 41, "developer", 0); var w2 = new Worker("John", 43, "developer", 0); //Test w1.giveBigRaise(); w1.salary; //?? w2.salary; //?? w1.getAge(); //?? w1.title == "Mr."; //?? w1 instance of Worker; //?? W2 instance of Worker; //?? w1 instance of Person; //?? w1 instance of Object; //??
  • 6. //Extending native types – forEach polyfill if (!Array.prototype.forEach) { Array.prototype.forEach = function (fn, scope) { for (var i = 0, l = this.length; i < l; ++i) { if (i in this) { fn.call(scope, this[i], i, this); } } }; } ['a','b','c'].forEach( function(elm, index, ctx) { console.log(index +'. ' + elm); }, window ); //Inheritance with Object.create var myMammal = { name : 'Herb the Mammal', get_name : function ( ) { return this.name; }, says : function ( ) { return this.saying || ''; } }; var myCat1 = createCat('Henrietta'); var myCat2 = createCat('Rocky'); function createCat(name) { var obj = Object.create(myMammal); obj.name = name; obj.saying = 'meow'; obj.purr = function (n) { return 'r-r-r-r-r'; }; obj.get_name = function ( ) { return this.says( ) + ' ' + this.name + ' '; }; return obj; } myCat2.get_name(); //?? myMammal.bloodTemperature = 'warm’; myCat1.bloodTemperature; //??
  • 7. //Functional Inheritance function base(spec) { var that = {}; that.name = spec.name; return that; // Return the object } function child(spec) { var that = base(spec); that.sayHello = function() { return 'Hello, I'm ' + that.name; }; return that; // Return it } // Usage var object = child({ name: 'a functional object' }); console.log(object.sayHello()); //Mixins var asButton = function() { this.hover = function() { console.log('hover handler'); }; this.press = function() { console.log('press handler'); }; this.fire = function() { return this.action(); }; return this; }; var asCircle = function() { this.area = function() { return Math.PI * this.radius * this.radius; }; this.grow = function() { this.radius++; }; this.shrink = function() { this.radius--; }; return this; }; var RoundButton = function(radius, label, action) { this.radius = radius; this.label = label; this.action = action; }; asButton.call(RoundButton.prototype); asCircle.call(RoundButton.prototype); var button1 = new RoundButton(4, 'yes!', function() {return 'you said yes!';} ); button1.fire(); //'you said yes!'
  • 8. Namespaces & Temp. Scope //Creating namespaces manually var afsi = afsi || {}; afsi.utilities = myApp.utilities || {}; afsi.utilities.sayHello = function(name) { return "Hi " + name; } //A namespace utility var afsi = afsi || {}; afsi.namespace = function namespace(namespaceString) { var parts = namespaceString.split('.'), parent = window, currentPart = ''; for(var i = 0, length = parts.length; i < length; i++) { currentPart = parts[i]; parent[currentPart] = parent[currentPart] || {}; parent = parent[currentPart]; } } //Defining and using a namespace afsi.namespace("afsi.utilities"); var afsi.utilities.sayHello = function(name) { return "Hi " + name; } //‘Wrapping’ techniques (function(){ var myLib = window.myLib = function(){ // Initialize }; // ... })(); --------------------------------------------- var myLib = (function(){ function myLib(){ // Initialize } // ... return myLib; })(); --------------------------------------------- (function( window, document, NS, undefined ){ NS.variableName = "string value"; NS.methodName = function() {}; // ... }(window, window.document, (window.NS = window.NS || {}) ) ); --------------------------------------------- function MyScript(){} (function() { var THIS = this; function defined(x) { alert(THIS); //points to MyScript() } // ... }).apply(MyScript);
  • 9. Module Pattern – (singleton, revealing) var afsi = afsi || {}; var afsi.calculator = (function () { var _m = 0; function _add(n1,n2) { return n1+n2; } function _substract(n1,n2) { return n1-n2; } function _setM(m) { return _m = m; } function _getM() { return _m; } return { add: _add, substract: _substract, setM: _setM, getM: _getM }; }());
  • 10. Module Pattern – constructor (OOP) var afsi = afsi || {}; afsi.MyClass = (function(){ var _privateStaticVar = "I am a static private variable"; var _privateFunction = function() { return "I am a private function"; }; var Constructor = function(options) { this.instanceVar = "I am an public instance variable"; this.setPrivateStaticVar = function(x) { _privateStaticVar = x; }; this.getPrivateStaticVar = function() { return _privateStaticVar; }; this.exposePrivateFunction = _privateFunction; }; Constructor.prototype = { constructor: afsi.MyClass, name: "afsi.MyClass", version: "1.0" }; return Constructor; }()); var v1 = new afsi.MyClass(options); var v2 = new afsi.MyClass(options);
  • 11. Module Pattern – factory (functional, revealing) var afsi = afsi || {}; afsi.calculator = (function(){ var _add = function (n1, n2) { return n1+n2; }; var _substract = function (n1, n2) { return n1-n2; }; var _calculatorFactory = function () { var _m = 0; var _setM = function (m) { _m = m; }; var _getM = function () { return _m; }; return { add: _add, substract: _substract, setM: _setM, getM: _getM }; }; return _calculatorFactory; }()); var calc = afsi.calculator();
  • 12. Dispatching (Publisher/Subscriber) var afsi = afsi || {}; afsi.messenger = (function () { var _messengerFactory = function() { var _messages = []; var _subscribeMessage = function (messageName, callBack) { if (typeof messageName === "string" && typeof callBack === "function") { if (typeof _messages[messageName] === "undefined") { _messages[messageName] = []; } _messages[messageName].push(callBack); } }; var _sendMessage = function (messageName, message) { if (typeof messageName === "string" && typeof _messages[messageName] !== "undefined") { for (var _counter = 0, max = _messages[messageName].length; _counter < max; _counter++) { _messages[messageName][_counter](message); } } }; return { subscribeMessage: _subscribeMessage, sendMessage: _sendMessage }; } return _messengerFactory; } ());
  • 13. Putting it all together //Controller afsi.namespace("afsi.myPage.controller"); afsi.myPage.controller = (function () { var _processSearchData (searchData) { //process the search data return searchData; } var _ctrFactory = function (model,view, messenger) { messenger.subscribeMessage( "myPage.search_onkeypress", function (text) { model.searchProducts(text); } ); messenger.subscribeMessage( "myPage.search_result", function (searchData) { searchData = _processSearchData(searchData); view.showSearchResult(searchData); } ); }; return _ctrFactory; } ()); //View afsi.namespace("afsi.myPage.view"); afsi.myPage.view = (function () { var _showSearchResult = function(searchData){ //bind UI with searchData … } var _viewFactory = function (messenger) { $("#searchInput").on("keypress", {}, function (event) { messenger.sendMessage( "myPage.search_onkeypress", this.value ); } ); return { showSearchResult: _showSearchResult }; } return _viewFactory } ());
  • 14. //Model afsi.namespace("afsi.myPage.model"); afsi.myPage.model = (function () { var _modelFactory = function (messenger) { var _searchProducts = function(text){ $.ajax({ url: "/api/Products/SearchProducts?q="+text, type: 'GET', cache: false, success: function (result) { messenger.sendMessage( "myPage.search_result", Result ); }, error: function (result) { alert("Some error message") } }); } return { searchProducts: _searchProducts }; } return _modelFactory; } ()); //Page initialization $(function () { var messenger = afsi.messenger(); afsi.myPage.controller( afsi.myPage.model(messenger), afsi.myPage.view(messenger), messenger ); });
  • 15. Unit Testing (QUnit) (function() { module('Dispatcher Test'); test( "Subscriber should be called and receceive the message", function() { //expected assertion # expect(3); //reate instance var m = afsi.messenger(); //set up m.subscribeMessage("afsi.test", function(message) { //assertions ok( true, "function called" ); ok( typeof message !== 'undefined', "message is defined" ); ok( message.data === 'something', "data has the correct value" ); }); //stimulus m.sendMessage("afsi.test", { data: 'something' }) }); … }());
  • 17. References Eloquent JavaScript http://eloquentjavascript.net/index.html Learning Advanced Javascript http://ejohn.org/apps/learn/ Google Talks: How JavaScript Works http://www.youtube.com/watch?v=ljNi8nS5TtQ Prototypes and Inheritance in JavaScript http://msdn.microsoft.com/en-us/magazine/ff852808.aspx Functional inheritance vs. prototypal inheritance http://www.richard-foy.fr/blog/2011/10/30/functional-inheritance-vs-prototypal-inheritance/ Namespacing in JavaScript http://javascriptweblog.wordpress.com/2010/12/07/namespacing-in-javascript/ JavaScript Module Pattern: In-Depth http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html ECMAScript 5 Strict Mode, JSON, and More http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/#! QUnit: Introduction to Unit Testing http://qunitjs.com/intro/ alert("Thank You!");