SlideShare a Scribd company logo
Intro to jQuery
Web Development 101
Lesson 03.01
jQuery is great
Advanced Javascript.
Web Development 101
Lesson 03.01
OR
What 80% of Javascript programmers don’t know
about their own language.
// The .bind method from Prototype.js	
Function.prototype.bind = function() {	
var fn = this,
args = Array.prototype.slice.call(arguments),
object = args.shift();	
return function() {	
return fn.apply(
object,
args.concat(
Array.prototype.slice.call(arguments)
)
);	
};	
};
What ways can we define functions?
function funcA(){ return true; }	
var funcB = function(){ return true; };	
window.funcC = function(){ return true; };
!

assert( funcA() && funcB() && funcC() );
var funcB = function(){ return true; };	
window.funcC = function(){ return true; };
!

assert( funcA() && funcB() && funcC() );
!

function funcA(){ return true; }
function stealthCheck(){	
assert( stealth() );	
!

return stealth();	
!

function stealth(){ return true; }	
}	
!

stealthCheck();
function factorial(n) {	
return n * (n > 1 ? factorial(n - 1) : 1);	
}	
!

factorial(10);
var factorial = function f(n) {	
return n * (n > 1 ? f(n - 1) : 1);	
}	
!

factorial(10); // Works
f(10);
// Undefined function
Is a function an object?
var obj = {};	
var fn = function(){};
!

obj.prop = "some value";	
fn.prop = "some value";
var factorial = function f(n) {	
f.cache = f.cache || {};	
if (!f.cache[n]) {	
f.cache[n] = n * (n > 1 ? f(n - 1) : 1);	
}	
return f.cache[n];	
}	
!

factorial(10);	
factorial(9);	
factorial(20);
How does `this` work?
var katana = {	
isSharp: true,	
use: function(){	
this.isSharp = false;	
}	
};	
!

katana.use();	
katana.isSharp === false;
function katana(){	
this.isSharp = true;	
}	
katana();	
isSharp === true;	
!
!

var shuriken = {	
toss: function(){	
this.isSharp = true;	
}	
};	
shuriken.toss();	
shuriken.isSharp === true;
How do I change `this`?
var object = {};	
function fn(){	
return this;	
}
!

fn() === this === window;
!

fn.call(object) === object;
var object = {a: ‘Jeremiah’, b: ‘Baruch’};
!

function getAttr(a){	
return this[a];	
}
!

getAttr.call(object, ‘a’) === ‘Jeremiah’;
!

getAttr.apply(object, [‘b’]) === ‘Baruch’;
Can I instantiate a function?
function Pioneer(){	
this.name = "Pioneer";	
}	
!

joe = Pioneer();	
joe === undefined;
!

joe = new Pioneer();
joe.name == "Pioneer";
function Pioneer(){	
this.hasBibleStudy = false;
!
this.preach = function() {
this.hasBibleStudy = true;	
};	
}	
!
jack = new Pioneer();
jill = new Pioneer();
!
jack.hasBibleStudy === false;
jill.hasBibleStudy === false;
!
jack.preach();
!
jack.hasBibleStudy === true;
jill.hasBibleStudy === false;
function Pioneer(){	
this.hasBibleStudy = false;
!
this.preach = function() {
this.hasBibleStudy = true;	
};	
}	
!
jack = Pioneer();
jill = Pioneer();
!
jack.hasBibleStudy === false; // Fatal Type Error
jill.hasBibleStudy === false;
!
jack.preach();
!
jack.hasBibleStudy === true;
jill.hasBibleStudy === false;
Can I build a function with variable
number of arguments?
var object = {a: ‘Jeremiah’, b: ‘Baruch’};
!

function getAttr(a){	
return this[a];	
}
!

getAttr.apply(object, [‘b’]) === ‘Baruch’;
var object = {a: ‘Jeremiah’, b: ‘Baruch’};
!

function getAttr() {
var out = [], i;
for (i = 0; i < arguments.length; i++) {
out.push( this[ arguments[i] ] );
}
return out;	
}
!

getAttr.apply(object, [‘a’, ‘b’]) ===
[‘Jeremiah’, ‘Baruch’];
function smallest(array){	
return Math.min.apply( Math, array );	
}
!

function largest(array){	
return Math.max.apply( Math, array );	
}
!

assert(smallest([0, 1, 2, 3]) == 0);	
assert(largest([0, 1, 2, 3]) == 3);
function smallest() {	
return Math.min.apply( Math, arguments );	
}
!

function largest() {	
return Math.max.apply( Math, arguments );	
}
!

assert(smallest(0, 1, 2, 3) == 0);	
assert(largest(0, 1, 2, 3) == 3);
function highest(){	
return arguments.sort(function(a, b) {	
return b - a;	
});	
}
!

highest(1, 1, 2, 3)[0] === 3;
function highest(){	
return arguments.sort(function(a, b) {	
return b - a;	
});	
}
!

highest(1, 1, 2, 3)[0] === 3; // Fatal Error.
`arguments` isn’t actually an array
function highest() {
var argArray = Array().slice.call(arguments);	
return argArray.sort(function(a, b) {	
return b - a;	
});	
}
!

highest(1, 1, 2, 3)[0] === 3;
How do Closures work?
var a = 5;

!
function runMe(a) {	
assert( a == ___, "Check the value of a." );	

!
function innerRun(){	
assert( b == ___, "Check the value of b." );	
assert( c == ___, "Check the value of c." );	
}	

!
var b = 7;	
innerRun();	
var c = 8;	
}

!
runMe(6);	

!
for ( var d = 0; d < 3; d++ ) {	
setTimeout(function(){	
assert( d == ___, "Check the value of d." );	
}, 100);	
}
var a = 5;

!
function runMe(a) {	
assert( a == 6, "Check the value of a." );	

!
function innerRun(){	
assert( b == 7, "Check the value of b." );	
assert( c == undefined, "Check the value of c." );	
}	

!
var b = 7;	
innerRun();	
var c = 8;	
}

!
runMe(6);	

!
for ( var d = 0; d < 3; d++ ) {	
setTimeout(function(){	
assert( d == 3, "Check the value of d." );	
}, 100);	
}
!

for ( var d = 0; d < 3; d++ ) {	
setTimeout(function(){	
assert( d == 3, "Check the value of d." );	
}, 100);	
}
for (var d = 0; d < 3; d++) {	
(function (d) {	
setTimeout(function () {	
console.log(d);	
}, 100);	
}(d));	
}
Code smell: Don’t make closures
inside a loop. Normally.
How do I make a class?
#!/usr/bin/env python
!

class Pioneer(object):
def __init__(self, name):
self.name = name
self.bibleStudies = 0
!

def preach(self):
self.bibleStudies += 1
!

joe = Pioneer(“Joe”)
joe.preach();
#!/usr/bin/env php
!
class Pioneer {
private name;
private bibleStudies;
!
public function __construct(name) {
this.name = name;
this.bibleStudies = 0;
}
!
public function preach() {
this.bibleStudies++;
}
}
!
joe = new Pioneer(“Joe”);
joe->preach();
Write `Pioneer` in JS.
var Pioneer = function(name) {
this.name = name;
this.bibleStudies = 0;
!

this.preach = function() {
this.bibleStudies++;
};
};
!

joe = new Pioneer(“Joe”);
joe.preach();
var Pioneer = function(name) {
this.name = name;
this.bibleStudies = 0;
};
!

Pioneer.prototype = {};
Pioneer.prototype.preach = function() {
this.bibleStudies++;
};
!

joe = new Pioneer(“Joe”);
joe.preach();
Inheritance. Prototypal Inheritance.
var Pioneer = function (name) {	
this.name = name;	
this.bibleStudies = 0;	
};	

!

Pioneer.prototype = {};	
Pioneer.prototype.preach = function () {	
this.bibleStudies++;	
};	

!

var SpecialPioneer = function(name) {	
this.name = name;	
this.bibleStudies = 0;	
};	

!

SpecialPioneer.prototype = new Pioneer();	
SpecialPioneer.prototype.preach = function () {	
this.bibleStudies += 5;	
};	

!

var joe = new Pioneer("Joe"),	
jeremy = new SpecialPioneer('Jeremy');	

!

joe.preach();	
jeremy.preach();
Enforcing Function Context
var Button = {	
click: function(){	
this.clicked = true;	
}	
};	
!

var elem = document.createElement("li");	
elem.innerHTML = "Click me!";	
elem.onclick = Button.click;	
document.getElementById("results").appendChild(elem);	
!

elem.onclick();
!

Button.clicked === undefined;	
elem.clicked === true;
function bind(context, name){	
return function() {	
return context[name].apply(context, arguments);	
};	
}	

!
var Button = {	
click: function(){	
this.clicked = true;	
}	
};	

!
var elem = document.createElement("li");	
elem.innerHTML = "Click me!";	
elem.onclick = bind(Button, "click");	
document.getElementById("results").appendChild(elem);	

!
elem.onclick();

!
Button.clicked === true;
elem.clicked === undefined;
Function.prototype.bind = function(object) {	
var fn = this;	
return function(){	
return fn.apply(object, arguments);	
};	
};	

!
var Button = {	
click: function(){	
this.clicked = true;	
}	
};	

!
var elem = document.createElement("li");	
elem.innerHTML = "Click me!";	
elem.onclick = Button.click.bind(Button);	
document.getElementById("results").appendChild(elem);	

!
elem.onclick();

!
Button.clicked === true;
Back to our original goal
// The .bind method from Prototype.js	
Function.prototype.bind = function() {	
var fn = this,
args = Array.prototype.slice.call(arguments),
object = args.shift();	
return function() {	
return fn.apply(
object,
args.concat(
Array.prototype.slice.call(arguments)
)
);	
};	
};
Function.prototype.bind = function(){	
var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift();	
return function(){	
return fn.apply(object,	
args.concat(Array.prototype.slice.call(arguments)));	
};	
};	

!
var Button = {	
click: function(value) {	
this.clicked = value;	
}	
};	

!
var elem = document.createElement("li");	
elem.innerHTML = "Click me!";	
elem.onclick = Button.click.bind(Button, “I was clicked!”);	
document.getElementById("results").appendChild(elem);	

!
elem.onclick();	

!
Button.clicked === “I was clicked!”
Functions can be defined 3
ways


Closures can be used to cache
values for later, including
execution scope.


Functions are just objects that
you can execute.


Objects inherit from each other
using prototypes.


The `this` keyword is bound to
function context


Build in object prototypes can
be extended.


No classes, just objects.


All of that works without
including jQuery at all.
Moral of the story
Javascript is a great, although quirky, language.

Prototypal inheritance works similarly, but not exactly like class
inheritance.

jQuery is a great library. You should use it for DOM and AJAX code.

Reading API documentation will teach you jQuery. A good
understanding of Javascript is harder to come by.
:rewind
var Pioneer = function (name) {	
this.name = name;	
this.bibleStudies = 0;	
};	

!

Pioneer.prototype = {};	
Pioneer.prototype.preach = function () {	
this.bibleStudies++;	
};	

!

var SpecialPioneer = function(name) {	
this.name = name;	
this.bibleStudies = 0;	
};	

!

SpecialPioneer.prototype = new Pioneer();	
SpecialPioneer.prototype.preach = function () {	
this.bibleStudies += 5;	
};	

!

var joe = new Pioneer("Joe"),	
jeremy = new SpecialPioneer('Jeremy');	

!

joe.preach();	
jeremy.preach();
Let’s make inheritance better.
var Person = Class.extend({	
init: function (isDancing) {	
this.dancing = isDancing;	
},	
dance: function () {	
return this.dancing;	
}	
});	

!

var Ninja = Person.extend({	
init: function () {	
this._super(false);	
},	
dance: function () {	
// Call the inherited version of dance()	
return this._super();	
},	
swingSword: function () {	
return true;	
}	
});	

!

var p = new Person(true);	
p.dance(); // => true	

!

var n = new Ninja();	
n.dance(); // => false	
n.swingSword(); // => true	

!

// Should all be true	
p instanceof Person && p instanceof Class && n instanceof Ninja && n instanceof Person && n instanceof Class

More Related Content

What's hot

Quick: Better Tests via Incremental Setup
Quick: Better Tests via Incremental SetupQuick: Better Tests via Incremental Setup
Quick: Better Tests via Incremental SetupBrian Gesiak
 
Testing view controllers with Quick and Nimble
Testing view controllers with Quick and NimbleTesting view controllers with Quick and Nimble
Testing view controllers with Quick and NimbleMarcio Klepacz
 
Containers & Dependency in Ember.js
Containers & Dependency in Ember.jsContainers & Dependency in Ember.js
Containers & Dependency in Ember.jsMatthew Beale
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptGuy Royse
 
Chaining et composition de fonctions avec lodash / underscore
Chaining et composition de fonctions avec lodash / underscoreChaining et composition de fonctions avec lodash / underscore
Chaining et composition de fonctions avec lodash / underscoreNicolas Carlo
 
UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기NAVER SHOPPING
 
Unbreakable: The Craft of Code
Unbreakable: The Craft of CodeUnbreakable: The Craft of Code
Unbreakable: The Craft of CodeJoe Morgan
 
The Spirit of Testing
The Spirit of TestingThe Spirit of Testing
The Spirit of TestingMarco Cedaro
 
ES6 patterns in the wild
ES6 patterns in the wildES6 patterns in the wild
ES6 patterns in the wildJoe Morgan
 
Clean code with google guava jee conf
Clean code with google guava jee confClean code with google guava jee conf
Clean code with google guava jee confIgor Anishchenko
 
An Introduction to the World of Testing for Front-End Developers
An Introduction to the World of Testing for Front-End DevelopersAn Introduction to the World of Testing for Front-End Developers
An Introduction to the World of Testing for Front-End DevelopersFITC
 
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...Haris Mahmood
 
Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Konstantin Kudryashov
 
Html and i_phone_mobile-2
Html and i_phone_mobile-2Html and i_phone_mobile-2
Html and i_phone_mobile-2tonvanbart
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptVisual Engineering
 

What's hot (18)

Quick: Better Tests via Incremental Setup
Quick: Better Tests via Incremental SetupQuick: Better Tests via Incremental Setup
Quick: Better Tests via Incremental Setup
 
Testing view controllers with Quick and Nimble
Testing view controllers with Quick and NimbleTesting view controllers with Quick and Nimble
Testing view controllers with Quick and Nimble
 
Containers & Dependency in Ember.js
Containers & Dependency in Ember.jsContainers & Dependency in Ember.js
Containers & Dependency in Ember.js
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
 
Chaining et composition de fonctions avec lodash / underscore
Chaining et composition de fonctions avec lodash / underscoreChaining et composition de fonctions avec lodash / underscore
Chaining et composition de fonctions avec lodash / underscore
 
UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기
 
QA for PHP projects
QA for PHP projectsQA for PHP projects
QA for PHP projects
 
Unbreakable: The Craft of Code
Unbreakable: The Craft of CodeUnbreakable: The Craft of Code
Unbreakable: The Craft of Code
 
The Spirit of Testing
The Spirit of TestingThe Spirit of Testing
The Spirit of Testing
 
ES6 patterns in the wild
ES6 patterns in the wildES6 patterns in the wild
ES6 patterns in the wild
 
Clean code with google guava jee conf
Clean code with google guava jee confClean code with google guava jee conf
Clean code with google guava jee conf
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
Deep dive into Oracle ADF
Deep dive into Oracle ADFDeep dive into Oracle ADF
Deep dive into Oracle ADF
 
An Introduction to the World of Testing for Front-End Developers
An Introduction to the World of Testing for Front-End DevelopersAn Introduction to the World of Testing for Front-End Developers
An Introduction to the World of Testing for Front-End Developers
 
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
FITC Web Unleashed 2017 - Introduction to the World of Testing for Front-End ...
 
Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015
 
Html and i_phone_mobile-2
Html and i_phone_mobile-2Html and i_phone_mobile-2
Html and i_phone_mobile-2
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
 

Similar to 04 Advanced Javascript

srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docxsrcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docxwhitneyleman54422
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptRyan Anklam
 
jQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyjQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyHuiyi Yan
 
Fat Arrow (ES6)
Fat Arrow (ES6)Fat Arrow (ES6)
Fat Arrow (ES6)Ryan Ewing
 
Object-oriented Javascript
Object-oriented JavascriptObject-oriented Javascript
Object-oriented JavascriptDaniel Ku
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript FunctionsColin DeCarlo
 
OO JS for AS3 Devs
OO JS for AS3 DevsOO JS for AS3 Devs
OO JS for AS3 DevsJason Hanson
 
JSConf: All You Can Leet
JSConf: All You Can LeetJSConf: All You Can Leet
JSConf: All You Can Leetjohndaviddalton
 
Modern JavaScript Engine Performance
Modern JavaScript Engine PerformanceModern JavaScript Engine Performance
Modern JavaScript Engine PerformanceCatalin Dumitru
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
Plugin jQuery, Design Patterns
Plugin jQuery, Design PatternsPlugin jQuery, Design Patterns
Plugin jQuery, Design PatternsRobert Casanova
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPresswpnepal
 
Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web ModuleMorgan Cheng
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developersStoyan Stefanov
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScriptkvangork
 

Similar to 04 Advanced Javascript (20)

srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docxsrcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
srcArtifact.javasrcArtifact.javaclassArtifactextendsCave{pub.docx
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScript
 
Introduccion a Jasmin
Introduccion a JasminIntroduccion a Jasmin
Introduccion a Jasmin
 
jQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyjQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journey
 
Fat Arrow (ES6)
Fat Arrow (ES6)Fat Arrow (ES6)
Fat Arrow (ES6)
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Object-oriented Javascript
Object-oriented JavascriptObject-oriented Javascript
Object-oriented Javascript
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
OO JS for AS3 Devs
OO JS for AS3 DevsOO JS for AS3 Devs
OO JS for AS3 Devs
 
JSConf: All You Can Leet
JSConf: All You Can LeetJSConf: All You Can Leet
JSConf: All You Can Leet
 
Modern JavaScript Engine Performance
Modern JavaScript Engine PerformanceModern JavaScript Engine Performance
Modern JavaScript Engine Performance
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
Plugin jQuery, Design Patterns
Plugin jQuery, Design PatternsPlugin jQuery, Design Patterns
Plugin jQuery, Design Patterns
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
 
Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web Module
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScript
 

More from crgwbr

Lightning Talk: Making JS better with Browserify
Lightning Talk: Making JS better with BrowserifyLightning Talk: Making JS better with Browserify
Lightning Talk: Making JS better with Browserifycrgwbr
 
07 Integration Project Part 1
07 Integration Project Part 107 Integration Project Part 1
07 Integration Project Part 1crgwbr
 
06 Map Reduce
06 Map Reduce06 Map Reduce
06 Map Reducecrgwbr
 
05 Web Services
05 Web Services05 Web Services
05 Web Servicescrgwbr
 
03 Web Events and jQuery
03 Web Events and jQuery03 Web Events and jQuery
03 Web Events and jQuerycrgwbr
 
02 Introduction to Javascript
02 Introduction to Javascript02 Introduction to Javascript
02 Introduction to Javascriptcrgwbr
 
01 Introduction To CSS
01 Introduction To CSS01 Introduction To CSS
01 Introduction To CSScrgwbr
 
08 Integration Project Part 2
08 Integration Project Part 208 Integration Project Part 2
08 Integration Project Part 2crgwbr
 

More from crgwbr (8)

Lightning Talk: Making JS better with Browserify
Lightning Talk: Making JS better with BrowserifyLightning Talk: Making JS better with Browserify
Lightning Talk: Making JS better with Browserify
 
07 Integration Project Part 1
07 Integration Project Part 107 Integration Project Part 1
07 Integration Project Part 1
 
06 Map Reduce
06 Map Reduce06 Map Reduce
06 Map Reduce
 
05 Web Services
05 Web Services05 Web Services
05 Web Services
 
03 Web Events and jQuery
03 Web Events and jQuery03 Web Events and jQuery
03 Web Events and jQuery
 
02 Introduction to Javascript
02 Introduction to Javascript02 Introduction to Javascript
02 Introduction to Javascript
 
01 Introduction To CSS
01 Introduction To CSS01 Introduction To CSS
01 Introduction To CSS
 
08 Integration Project Part 2
08 Integration Project Part 208 Integration Project Part 2
08 Integration Project Part 2
 

Recently uploaded

Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Product School
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...Product School
 
Introduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationIntroduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationZilliz
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...Product School
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeCzechDreamin
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxDavid Michel
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsPaul Groth
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxJennifer Lim
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityScyllaDB
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...Product School
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Product School
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCzechDreamin
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backElena Simperl
 
In-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsIn-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsExpeed Software
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomCzechDreamin
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlPeter Udo Diehl
 
Agentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfAgentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfChristopherTHyatt
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Thierry Lestable
 

Recently uploaded (20)

Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Introduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationIntroduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG Evaluation
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through Observability
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
In-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsIn-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT Professionals
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
Agentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfAgentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdf
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 

04 Advanced Javascript

  • 1. Intro to jQuery Web Development 101 Lesson 03.01
  • 3.
  • 5. OR What 80% of Javascript programmers don’t know about their own language.
  • 6. // The .bind method from Prototype.js Function.prototype.bind = function() { var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift(); return function() { return fn.apply( object, args.concat( Array.prototype.slice.call(arguments) ) ); }; };
  • 7. What ways can we define functions?
  • 8. function funcA(){ return true; } var funcB = function(){ return true; }; window.funcC = function(){ return true; }; ! assert( funcA() && funcB() && funcC() );
  • 9. var funcB = function(){ return true; }; window.funcC = function(){ return true; }; ! assert( funcA() && funcB() && funcC() ); ! function funcA(){ return true; }
  • 10. function stealthCheck(){ assert( stealth() ); ! return stealth(); ! function stealth(){ return true; } } ! stealthCheck();
  • 11. function factorial(n) { return n * (n > 1 ? factorial(n - 1) : 1); } ! factorial(10);
  • 12. var factorial = function f(n) { return n * (n > 1 ? f(n - 1) : 1); } ! factorial(10); // Works f(10); // Undefined function
  • 13. Is a function an object?
  • 14. var obj = {}; var fn = function(){}; ! obj.prop = "some value"; fn.prop = "some value";
  • 15. var factorial = function f(n) { f.cache = f.cache || {}; if (!f.cache[n]) { f.cache[n] = n * (n > 1 ? f(n - 1) : 1); } return f.cache[n]; } ! factorial(10); factorial(9); factorial(20);
  • 17. var katana = { isSharp: true, use: function(){ this.isSharp = false; } }; ! katana.use(); katana.isSharp === false;
  • 18. function katana(){ this.isSharp = true; } katana(); isSharp === true; ! ! var shuriken = { toss: function(){ this.isSharp = true; } }; shuriken.toss(); shuriken.isSharp === true;
  • 19. How do I change `this`?
  • 20. var object = {}; function fn(){ return this; } ! fn() === this === window; ! fn.call(object) === object;
  • 21. var object = {a: ‘Jeremiah’, b: ‘Baruch’}; ! function getAttr(a){ return this[a]; } ! getAttr.call(object, ‘a’) === ‘Jeremiah’; ! getAttr.apply(object, [‘b’]) === ‘Baruch’;
  • 22. Can I instantiate a function?
  • 23. function Pioneer(){ this.name = "Pioneer"; } ! joe = Pioneer(); joe === undefined; ! joe = new Pioneer(); joe.name == "Pioneer";
  • 24. function Pioneer(){ this.hasBibleStudy = false; ! this.preach = function() { this.hasBibleStudy = true; }; } ! jack = new Pioneer(); jill = new Pioneer(); ! jack.hasBibleStudy === false; jill.hasBibleStudy === false; ! jack.preach(); ! jack.hasBibleStudy === true; jill.hasBibleStudy === false;
  • 25. function Pioneer(){ this.hasBibleStudy = false; ! this.preach = function() { this.hasBibleStudy = true; }; } ! jack = Pioneer(); jill = Pioneer(); ! jack.hasBibleStudy === false; // Fatal Type Error jill.hasBibleStudy === false; ! jack.preach(); ! jack.hasBibleStudy === true; jill.hasBibleStudy === false;
  • 26. Can I build a function with variable number of arguments?
  • 27. var object = {a: ‘Jeremiah’, b: ‘Baruch’}; ! function getAttr(a){ return this[a]; } ! getAttr.apply(object, [‘b’]) === ‘Baruch’;
  • 28. var object = {a: ‘Jeremiah’, b: ‘Baruch’}; ! function getAttr() { var out = [], i; for (i = 0; i < arguments.length; i++) { out.push( this[ arguments[i] ] ); } return out; } ! getAttr.apply(object, [‘a’, ‘b’]) === [‘Jeremiah’, ‘Baruch’];
  • 29. function smallest(array){ return Math.min.apply( Math, array ); } ! function largest(array){ return Math.max.apply( Math, array ); } ! assert(smallest([0, 1, 2, 3]) == 0); assert(largest([0, 1, 2, 3]) == 3);
  • 30. function smallest() { return Math.min.apply( Math, arguments ); } ! function largest() { return Math.max.apply( Math, arguments ); } ! assert(smallest(0, 1, 2, 3) == 0); assert(largest(0, 1, 2, 3) == 3);
  • 31. function highest(){ return arguments.sort(function(a, b) { return b - a; }); } ! highest(1, 1, 2, 3)[0] === 3;
  • 32. function highest(){ return arguments.sort(function(a, b) { return b - a; }); } ! highest(1, 1, 2, 3)[0] === 3; // Fatal Error.
  • 34. function highest() { var argArray = Array().slice.call(arguments); return argArray.sort(function(a, b) { return b - a; }); } ! highest(1, 1, 2, 3)[0] === 3;
  • 36. var a = 5; ! function runMe(a) { assert( a == ___, "Check the value of a." ); ! function innerRun(){ assert( b == ___, "Check the value of b." ); assert( c == ___, "Check the value of c." ); } ! var b = 7; innerRun(); var c = 8; } ! runMe(6); ! for ( var d = 0; d < 3; d++ ) { setTimeout(function(){ assert( d == ___, "Check the value of d." ); }, 100); }
  • 37. var a = 5; ! function runMe(a) { assert( a == 6, "Check the value of a." ); ! function innerRun(){ assert( b == 7, "Check the value of b." ); assert( c == undefined, "Check the value of c." ); } ! var b = 7; innerRun(); var c = 8; } ! runMe(6); ! for ( var d = 0; d < 3; d++ ) { setTimeout(function(){ assert( d == 3, "Check the value of d." ); }, 100); }
  • 38. ! for ( var d = 0; d < 3; d++ ) { setTimeout(function(){ assert( d == 3, "Check the value of d." ); }, 100); }
  • 39. for (var d = 0; d < 3; d++) { (function (d) { setTimeout(function () { console.log(d); }, 100); }(d)); }
  • 40. Code smell: Don’t make closures inside a loop. Normally.
  • 41. How do I make a class?
  • 42. #!/usr/bin/env python ! class Pioneer(object): def __init__(self, name): self.name = name self.bibleStudies = 0 ! def preach(self): self.bibleStudies += 1 ! joe = Pioneer(“Joe”) joe.preach();
  • 43. #!/usr/bin/env php ! class Pioneer { private name; private bibleStudies; ! public function __construct(name) { this.name = name; this.bibleStudies = 0; } ! public function preach() { this.bibleStudies++; } } ! joe = new Pioneer(“Joe”); joe->preach();
  • 45. var Pioneer = function(name) { this.name = name; this.bibleStudies = 0; ! this.preach = function() { this.bibleStudies++; }; }; ! joe = new Pioneer(“Joe”); joe.preach();
  • 46. var Pioneer = function(name) { this.name = name; this.bibleStudies = 0; }; ! Pioneer.prototype = {}; Pioneer.prototype.preach = function() { this.bibleStudies++; }; ! joe = new Pioneer(“Joe”); joe.preach();
  • 48. var Pioneer = function (name) { this.name = name; this.bibleStudies = 0; }; ! Pioneer.prototype = {}; Pioneer.prototype.preach = function () { this.bibleStudies++; }; ! var SpecialPioneer = function(name) { this.name = name; this.bibleStudies = 0; }; ! SpecialPioneer.prototype = new Pioneer(); SpecialPioneer.prototype.preach = function () { this.bibleStudies += 5; }; ! var joe = new Pioneer("Joe"), jeremy = new SpecialPioneer('Jeremy'); ! joe.preach(); jeremy.preach();
  • 50. var Button = { click: function(){ this.clicked = true; } }; ! var elem = document.createElement("li"); elem.innerHTML = "Click me!"; elem.onclick = Button.click; document.getElementById("results").appendChild(elem); ! elem.onclick(); ! Button.clicked === undefined; elem.clicked === true;
  • 51. function bind(context, name){ return function() { return context[name].apply(context, arguments); }; } ! var Button = { click: function(){ this.clicked = true; } }; ! var elem = document.createElement("li"); elem.innerHTML = "Click me!"; elem.onclick = bind(Button, "click"); document.getElementById("results").appendChild(elem); ! elem.onclick(); ! Button.clicked === true; elem.clicked === undefined;
  • 52. Function.prototype.bind = function(object) { var fn = this; return function(){ return fn.apply(object, arguments); }; }; ! var Button = { click: function(){ this.clicked = true; } }; ! var elem = document.createElement("li"); elem.innerHTML = "Click me!"; elem.onclick = Button.click.bind(Button); document.getElementById("results").appendChild(elem); ! elem.onclick(); ! Button.clicked === true;
  • 53. Back to our original goal
  • 54. // The .bind method from Prototype.js Function.prototype.bind = function() { var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift(); return function() { return fn.apply( object, args.concat( Array.prototype.slice.call(arguments) ) ); }; };
  • 55. Function.prototype.bind = function(){ var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift(); return function(){ return fn.apply(object, args.concat(Array.prototype.slice.call(arguments))); }; }; ! var Button = { click: function(value) { this.clicked = value; } }; ! var elem = document.createElement("li"); elem.innerHTML = "Click me!"; elem.onclick = Button.click.bind(Button, “I was clicked!”); document.getElementById("results").appendChild(elem); ! elem.onclick(); ! Button.clicked === “I was clicked!”
  • 56.
  • 57. Functions can be defined 3 ways Closures can be used to cache values for later, including execution scope. Functions are just objects that you can execute. Objects inherit from each other using prototypes. The `this` keyword is bound to function context Build in object prototypes can be extended. No classes, just objects. All of that works without including jQuery at all.
  • 58. Moral of the story
  • 59. Javascript is a great, although quirky, language. Prototypal inheritance works similarly, but not exactly like class inheritance. jQuery is a great library. You should use it for DOM and AJAX code. Reading API documentation will teach you jQuery. A good understanding of Javascript is harder to come by.
  • 61. var Pioneer = function (name) { this.name = name; this.bibleStudies = 0; }; ! Pioneer.prototype = {}; Pioneer.prototype.preach = function () { this.bibleStudies++; }; ! var SpecialPioneer = function(name) { this.name = name; this.bibleStudies = 0; }; ! SpecialPioneer.prototype = new Pioneer(); SpecialPioneer.prototype.preach = function () { this.bibleStudies += 5; }; ! var joe = new Pioneer("Joe"), jeremy = new SpecialPioneer('Jeremy'); ! joe.preach(); jeremy.preach();
  • 63. var Person = Class.extend({ init: function (isDancing) { this.dancing = isDancing; }, dance: function () { return this.dancing; } }); ! var Ninja = Person.extend({ init: function () { this._super(false); }, dance: function () { // Call the inherited version of dance() return this._super(); }, swingSword: function () { return true; } }); ! var p = new Person(true); p.dance(); // => true ! var n = new Ninja(); n.dance(); // => false n.swingSword(); // => true ! // Should all be true p instanceof Person && p instanceof Class && n instanceof Ninja && n instanceof Person && n instanceof Class